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

ASP.NET Core JWT签发者签名密钥验证失败报401排查

问题描述

报错信息:Fail to validate issuer signing key for JWT
现有一个被[Authorize]特性保护的接口端点,预期访问规则:请求携带使用字符串Super-Secret-Key签名的JWT令牌时,允许访问该端点。
目前通过Jwt.io工具生成对应令牌(令牌配置见文末截图),但使用Postman将编码后的令牌作为Bearer令牌发起请求访问端点时,始终返回401 Unauthorized错误,需排查现有配置遗漏点。

现有Program.cs配置

var tokenValidationParameters = new TokenValidationParameters
{
    ValidateAudience = false,
    ValidateLifetime = false,
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Super-Secret-Key"))
};

var builder = WebApplication.CreateBuilder(args);
{ 
    builder.Services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => options.TokenValidationParameters = tokenValidationParameters);

    builder.Services.AddAuthorization();
    builder.Services.AddControllers();
}

(...)

Jwt.io中令牌配置截图


问题原因

核心问题是Jwt.io端配置和服务端密钥处理逻辑不匹配:

  • Jwt.io生成令牌时勾选了输入框下方的secret base64 encoded选项,勾选后平台会将输入的Super-Secret-Key当做Base64编码字符串解码,用解码后的字节值作为签名密钥;
  • 服务端代码直接通过Encoding.UTF8.GetBytes("Super-Secret-Key")将原字符串转成UTF8字节作为密钥,两边用于签名/验签的密钥值完全不一致,直接导致签名校验失败返回401。

配置存在额外遗漏:当前TokenValidationParameters未显式关闭发行者校验,ValidateIssuer默认值为true,如果JWT令牌携带的iss声明和服务端配置的ValidIssuer不匹配,后续也会触发校验失败。
同时需确认中间件管道顺序:必须在app.UseAuthorization()之前调用app.UseAuthentication(),否则认证中间件不会执行,同样会返回401。


修复方案
  • 修正Jwt.io配置:取消勾选secret base64 encoded复选框,重新生成令牌,保证签名使用的密钥是Super-Secret-Key的原始UTF8编码字节,和服务端逻辑对齐。
  • 补全Token校验参数:如果不需要校验发行者,显式将ValidateIssuer设为false,避免额外校验拦截,修改后参数配置如下:
var tokenValidationParameters = new TokenValidationParameters
{
    ValidateAudience = false,
    ValidateLifetime = false,
    ValidateIssuer = false,
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Super-Secret-Key"))
};
  • 检查中间件顺序:确保Program.cs中中间件注册顺序符合要求,认证中间件必须放在授权、控制器映射之前,示例如下:
var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

内容的提问来源于stack exchange,提问作者Jakob Busk Sørensen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:54:30