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

.NET Core Web API添加Identity后[Authorize]失效问题咨询

问题原因与解决方案

嘿,这个问题我之前也碰到过!确实,services.AddIdentity和你配置的JWT认证之间存在冲突,核心原因是AddIdentity会自动注册Cookie认证并将其设为默认的AuthenticationScheme——而你之前只使用JWT时,默认认证方案是JWT,所以[Authorize]能正常校验。加了Identity后,默认方案被改成了Cookie,你的JWT令牌自然就不被识别了。

下面给你几种针对性的解决办法:

1. 纯API场景:用AddIdentityCore替代AddIdentity

如果你的项目是纯Web API,不需要Identity提供的Cookie登录功能,推荐用AddIdentityCore代替AddIdentity。它只会注册Identity的核心服务(比如UserManager、SignInManager),不会自动添加Cookie认证,这样就不会干扰你的JWT配置:

// 注册Identity核心服务
services.AddIdentityCore<ApplicationUser>(options => 
{
    options.SignIn.RequireConfirmedAccount = true;
    // 其他Identity配置项
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

// 配置JWT并设为默认认证方案
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });

2. 混合场景(API+MVC页面):手动指定默认认证方案

如果你的项目同时需要Cookie认证(比如有后台管理页面)和JWT认证,那可以手动把默认认证方案设为JWT,这样[Authorize]会优先用JWT校验API请求,而Cookie可以用于页面登录:

// 先配置认证,明确设置默认方案为JWT
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    // JWT配置同上
})
.AddCookie(options =>
{
    // 这里可以配置Cookie认证的参数,比如登录路径等(如果需要)
});

// 再正常注册Identity
services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

另外,你也可以在需要JWT校验的控制器/Action上,直接指定认证Scheme:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[ApiController]
[Route("api/[controller]")]
public class YourController : ControllerBase
{
    // ...
}

3. 检查中间件顺序

最后别忘了确认中间件的顺序,这也是很多人踩坑的点:app.UseAuthentication()必须在app.UseAuthorization()之前,而且要放在app.UseRouting()之后,正确的顺序如下:

app.UseRouting();

// 认证要在授权之前
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

只要调整好这些配置,你的[Authorize]属性就能正常校验JWT令牌了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:49:55