AspNet Core如何同时使用Firebase JWT认证与原生Identity认证
解决方案
你当前的配置将JWT Bearer设为了全局唯一默认认证方案,因此所有请求默认都会走Firebase JWT校验逻辑,原有AspNet Core Identity依赖的Cookie认证方案不会被自动触发,才会导致原有Identity认证失效。
第一步:修改认证服务注册配置
保留原有Identity的注册代码,给Firebase JWT认证指定独立的自定义方案名,不覆盖全局默认配置:
// 保留原有Identity注册逻辑,不要删除 services.AddDefaultIdentity<IdentityUser>(options => { // 你的原有Identity配置项 }) .AddEntityFrameworkStores<ApplicationDbContext>(); // 注册Firebase JWT认证,指定独立方案名 services.AddAuthentication() .AddJwtBearer("FirebaseJwt", options => { options.Authority = "xxx"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "xxx", ValidateAudience = true, ValidAudience = "xxx", ValidateLifetime = true }; });
注意:代码中用到的IdentityConstants需要引入命名空间Microsoft.AspNetCore.Identity
第二步:两种实现方案二选一
方案1:手动给Controller指定认证方案
- 普通使用Identity认证的Controller,直接添加默认
[Authorize]注解即可,会自动走Identity的Cookie认证逻辑 - API接口的Controller,添加指定方案的注解:
[Authorize(AuthenticationSchemes = "FirebaseJwt")]即可走Firebase JWT校验 - 如果有接口需要同时支持两种认证方式,可指定多方案:
[Authorize(AuthenticationSchemes = $"{IdentityConstants.ApplicationScheme},FirebaseJwt")]
方案2:批量配置授权策略(更推荐)
无需逐个给Controller加注解,可通过授权策略+路由规则批量匹配:
- 先注册授权策略:
services.AddAuthorization(options => { // API专用Firebase认证策略 options.AddPolicy("FirebaseApiPolicy", policy => { policy.AuthenticationSchemes.Add("FirebaseJwt"); policy.RequireAuthenticatedUser(); }); // 普通页面专用Identity认证策略 options.AddPolicy("IdentityPagePolicy", policy => { policy.AuthenticationSchemes.Add(IdentityConstants.ApplicationScheme); policy.RequireAuthenticatedUser(); }); });
- 在路由配置中批量应用策略:
// /api开头的路由统一应用Firebase认证策略 app.MapControllerRoute( name: "api", pattern: "api/{controller=Home}/{action=Index}/{id?}") .RequireAuthorization("FirebaseApiPolicy"); // 普通页面路由统一应用Identity认证策略 app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}") .RequireAuthorization("IdentityPagePolicy");
内容的提问来源于stack exchange,提问作者Stefano Toppi
相关产品推荐
相关产品推荐

