You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁止访问ASP.NET Core 8 Identity自动生成的指定端点?

禁止ASP.NET Core Identity未使用端点的两种实现方式

方法一:自定义拦截中间件(快速拦截指定路径)

在Program.cs的请求管道中添加自定义中间件,直接拦截目标路径并返回403。这种方式简单直接,适合批量拦截多个端点:

var builder = WebApplication.CreateBuilder(args);

// 配置基础服务
builder.Services.AddControllersWithViews();
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders()
    .AddDefaultUI();

var app = builder.Build();

// 环境相关配置
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

// 添加拦截中间件(必须放在UseRouting之后,UseAuthorization之前)
var blockedEndpoints = new HashSet<string>
{
    "/Register",
    "/Account/Register",
    "/ForgotPassword",
    "/Account/ForgotPassword"
};

app.Use(async (context, next) =>
{
    if (blockedEndpoints.Any(path => 
        context.Request.Path.StartsWithSegments(path, StringComparison.OrdinalIgnoreCase)))
    {
        context.Response.StatusCode = StatusCodes.Status403Forbidden;
        await context.Response.WriteAsync("Access Denied");
        return;
    }
    await next();
});

app.UseAuthorization();

// 路由映射
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run();

方法二:针对Razor Pages精确控制(推荐用于Identity页面)

Identity的UI基于Razor Pages,可以通过配置RazorPagesOptions直接对指定页面添加拦截规则,这种方式更贴合Identity的设计:

var builder = WebApplication.CreateBuilder(args);

// 配置Razor Pages拦截规则
builder.Services.AddRazorPages(options =>
{
    // 禁止访问注册页面
    options.Conventions.ForPage("/Account/Register").AddFilter(new AuthorizeFilter(
        new AuthorizationPolicyBuilder()
            .RequireAssertion(_ => false) // 断言永远不通过,直接拒绝访问
            .Build()));
    
    // 如需禁止其他页面,重复上述配置
    options.Conventions.ForPage("/Account/ForgotPassword").AddFilter(new AuthorizeFilter(
        new AuthorizationPolicyBuilder()
            .RequireAssertion(_ => false)
            .Build()));
});

// 配置Identity服务
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders()
    .AddDefaultUI();

var app = builder.Build();

// 环境相关配置
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

// 路由映射
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run();

注意事项

  • 确认Identity页面的实际路由:默认情况下,Identity UI的页面路由前缀为/Account(如注册页是/Account/Register),部分场景下可能存在简化路由/Register,需根据实际情况补充到拦截列表。
  • 中间件顺序:自定义拦截中间件必须放在UseRouting之后、UseAuthorization之前,才能确保请求被优先拦截。

内容的提问来源于stack exchange,提问作者Tom Clark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 09:22:41