如何让.NET 8极简Identity API适配全局授权FallbackPolicy?
解决.NET 8 Identity端点受全局FallbackPolicy影响的问题
当然可以自定义.NET 8 Identity端点的授权规则,以下是几种可行的方案:
方案一:配置Identity端点时直接添加AllowAnonymous元数据
在调用MapIdentityApi时,通过配置项为指定端点(比如/register)添加AllowAnonymousAttribute,直接绕过全局FallbackPolicy:
builder.Services.AddIdentityApiEndpoints<IdentityUser>() .AddEntityFrameworkStores<ApplicationDbContext>(); // 自定义Identity端点的授权设置 app.MapIdentityApi<IdentityUser>(options => { // 为注册端点添加AllowAnonymous options.RegisterEndpoint(endpoint => { endpoint.WithMetadata(new AllowAnonymousAttribute()); }); // 同理可给其他公开端点(如/login、/forgotPassword)添加相同配置 options.LoginEndpoint(endpoint => { endpoint.WithMetadata(new AllowAnonymousAttribute()); }); });
方案二:批量为指定Identity端点添加授权元数据
如果需要一次性处理多个公开的Identity端点,可以遍历生成的端点集合,筛选目标路径后添加AllowAnonymous:
var identityEndpointGroup = app.MapIdentityApi<IdentityUser>(); // 筛选需要豁免授权的端点路径 var publicPaths = new[] { "/register", "/login", "/forgotPassword", "/resetPassword" }; foreach (var endpoint in identityEndpointGroup.Where(e => publicPaths.Any(path => e.RoutePattern.RawText.Contains(path)))) { endpoint.WithMetadata(new AllowAnonymousAttribute()); }
方案三:调整全局FallbackPolicy排除特定路径
如果不想逐个配置端点,也可以修改全局FallbackPolicy,通过断言排除公开路径:
builder.Services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .RequireAssertion(context => { var httpContext = context.Resource as HttpContext; if (httpContext == null) return false; // 排除公开的Identity端点路径 var isPublicEndpoint = httpContext.Request.Path.StartsWithSegments("/register") || httpContext.Request.Path.StartsWithSegments("/login") || httpContext.Request.Path.StartsWithSegments("/forgotPassword"); return isPublicEndpoint || context.User.Identity?.IsAuthenticated == true; }) .Build(); });
推荐方案
优先选择方案一,因为它是.NET 8 Identity端点提供的官方扩展方式,配置更精准、可读性更强,也便于后续维护。
内容的提问来源于stack exchange,提问作者Saeb Amini
相关产品推荐
相关产品推荐

