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

ASP.NET Core 5 JWT认证访问带[Authorize]属性接口返回401错误如何解决

问题原因及修复方案

核心问题1:JWT生成与验证的配置不匹配

你在JWT验证配置中开启了ValidateIssuer和ValidateAudience校验,并且指定了有效值为whatever,但生成JWT的SecurityTokenDescriptor中没有对应设置Issuer和Audience属性,导致验证时匹配失败直接返回401。
修复方法:修改生成Token的代码,补充对应配置即可:

SecurityTokenDescriptor tokenDescriptor = new()
{
    Subject            = new ClaimsIdentity(new[] { new Claim("UserName", user.UserName) }),
    Expires            = DateTime.UtcNow.AddDays(7),
    SigningCredentials = new SigningCredentials(encryptionKey, SecurityAlgorithms.HmacSha256Signature),
    // 补充和验证配置一致的Issuer和Audience
    Issuer = "whatever",
    Audience = "whatever"
};

如果不需要校验签发者和受众,也可以直接把TokenValidationParameters中的ValidateIssuer和ValidateAudience设为false,但生产环境不推荐该操作。

核心问题2:中间件执行顺序错误

ASP.NET Core的中间件执行顺序对身份认证逻辑有严格要求,你当前Configure方法中的顺序是UseAuthentication -> UseRouting,正确顺序应该是先完成路由匹配,再执行身份认证逻辑:
修复方法:调整中间件顺序如下:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if(env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting(); // 先执行路由匹配
    app.UseAuthentication(); // 再执行身份认证
    app.UseAuthorization(); // 最后执行授权校验
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

可选补充:适配UserManager获取用户逻辑

你后续调用_userManager.GetUserAsync(User)时,默认会读取ClaimTypes.NameIdentifier类型的Claim获取用户ID,你当前只添加了UserName类型的Claim,会导致该方法返回null,建议生成Token时补充必要的Claim:

Subject = new ClaimsIdentity(new[] 
{ 
    new Claim(ClaimTypes.Name, user.UserName),
    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) // 补充用户ID的Claim
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:54:04