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

ASP.NET Core 8 Web API中JWT Token始终无效的问题求助

ASP.NET Core 8 Web API JWT认证报错:Bearer error="invalid_token"

Bearer error="invalid_token"

已通过jwt.io验证Token格式正常,Chrome网络面板未发现请求异常,但严格按教程配置后仍无法完成认证。

问题根源与修复方案

1. 配置默认认证方案

Program.cs中AddAuthentication未指定默认认证方案,导致中间件无法确定使用JWT Bearer验证Token。

修改前:

builder.Services.AddAuthentication().AddJwtBearer(options => {
    // 现有配置
});

修改后(需先添加using Microsoft.AspNetCore.Authentication.JwtBearer;命名空间):

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        options.TokenValidationParameters = new TokenValidationParameters{
            ValidateIssuerSigningKey = true,
            ValidateAudience = false,
            ValidateIssuer = false,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(
                    builder.Configuration.GetSection("AppSettings:Token").Value!
                )
            ),
            // 显式指定算法,避免匹配错误
            ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha512Signature }
        };
    });

2. 修复Swagger安全定义配置

当前Swagger的安全定义类型错误,导致Token传递不符合规范。

修改Program.cs中AddSwaggerGen配置:

builder.Services.AddSwaggerGen(options => {
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme{
        In = ParameterLocation.Header,
        Name = "Authorization",
        Type = SecuritySchemeType.Http,
        Scheme = "bearer",
        BearerFormat = "JWT",
        Description = "JWT认证格式:Bearer {Token}"
    });
    
    options.OperationFilter<SecurityRequirementsOperationFilter>();
});

3. 确保算法一致性

JWT.cs中使用SecurityAlgorithms.HmacSha512Signature生成Token,需保证验证阶段使用相同算法,上述ValidAlgorithms配置已覆盖此要求。

4. 确认中间件顺序

保证中间件执行顺序正确:

app.UseCors();
app.UseAuthentication(); // 必须在UseAuthorization之前
app.UseAuthorization();
app.MapControllers();

额外排查项

  • 确认appsettings.json中AppSettings:Token密钥在生成和验证时完全一致,无大小写、空格差异
  • 检查Token是否过期(当前配置为12小时有效期)
  • 开启调试日志排查细节,在appsettings.json中添加:
"Logging": {
    "LogLevel": {
        "Default": "Information",
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.IdentityModel": "Debug"
    }
}

内容的提问来源于stack exchange,提问作者Lars S.K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 01:45:55