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

.NET8 ASP.NET Core Web API JWT无效令牌401错误求助

ASP.NET Core 8 Web API:JWT令牌验证失败(401 Bearer error="invalid_token")

问题概述

开发ASP.NET Core 8 Web API项目,集成JWT令牌认证。登录接口可正常生成令牌,且令牌在第三方JWT调试网站验证通过,但调用带有授权验证的Weather控制器时,始终返回401未授权错误,响应头包含Bearer error="invalid_token"。怀疑问题出在控制器实现或Postman调用方式上,已提供AuthController、Program.cs代码及项目仓库。

关键代码片段

Program.cs 认证配置部分

// 替换为项目实际代码
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

builder.Services.AddAuthorization();

// 确认中间件顺序
app.UseAuthentication();
app.UseAuthorization();

AuthController 登录生成令牌部分

// 替换为项目实际代码
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
    // 用户验证逻辑(省略)
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, model.Username),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: _configuration["Jwt:Issuer"],
        audience: _configuration["Jwt:Audience"],
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: creds);

    return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token) });
}

WeatherController 授权配置

[ApiController]
[Route("[controller]")]
[Authorize] // 确认是否添加该属性
public class WeatherController : ControllerBase
{
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        // 接口逻辑(省略)
    }
}

排查建议

  • 核对JWT参数一致性:确保生成令牌时使用的Issuer、Audience、SigningKey与Program.cs中TokenValidationParameters的配置完全一致,包括大小写、字符编码(如UTF8)
  • 检查Postman请求格式:确认Authorization头的值为Bearer {你的令牌},注意Bearer与令牌之间有且仅有一个空格,无多余空格或特殊字符;避免在令牌前后添加引号
  • 验证令牌有效期:通过JWT调试网站查看令牌的exp字段,确认请求时令牌未过期
  • 确认中间件顺序:Program.cs中UseAuthentication()必须在UseAuthorization()之前调用,否则认证逻辑不会生效
  • 查看详细错误日志:在appsettings.json中启用认证相关Debug日志,获取invalid_token的具体原因:
    {
      "Logging": {
        "LogLevel": {
          "Microsoft.AspNetCore.Authentication": "Debug"
        }
      }
    }
    
  • 检查授权策略:如果WeatherController使用[Authorize(Policy = "xxx")],需确认生成的令牌包含该策略要求的Claims
  • 验证签名算法一致性:确保生成令牌时使用的签名算法(如HmacSha256)与Program.cs中配置的一致

内容的提问来源于stack exchange,提问作者Shaik Abid Hussain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:42:27