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

ASP.NET Core 8集成JWT鉴权报签名无效401错误求助

ASP.NET Core 8 JWT鉴权401(无效签名)问题解决

问题场景

使用ASP.NET Core 6开发的JWT令牌生成服务,可为其他应用正常鉴权,但新创建的ASP.NET Core 8应用接入后,所有请求均返回401错误,错误响应为:

Bearer error="invalid_token",error_description="The signature is invalid"

令牌生成代码(ASP.NET Core 6)

public TokenDTO GetToken(string id)
{
    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.NameId, id),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    };

    var roles = _aplicacionRepository.ObtenerPermisos(id);
    foreach (var rol in roles)
    {
        claims.Add(new Claim(ClaimTypes.Role, rol.Codigo));
    }

    var key = Encoding.ASCII.GetBytes(_settings.Value.Key);

    var token = new JwtSecurityToken(
        issuer: _settings.Value.Issuer,
        audience: _settings.Value.Audience,
        claims: claims.ToArray(),
        expires: DateTime.UtcNow.AddMinutes(_settings.Value.TokenExpirationMinutes),
        signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
    );

    var tokenHandler = new JwtSecurityTokenHandler();

    return new TokenDTO()
    {
        access_token = tokenHandler.WriteToken(token),
        expires_in = _settings.Value.TokenExpirationMinutes * 60,
        token_type = "bearer"
    };
}

鉴权配置代码(ASP.NET Core 8)

services.AddAuthentication(def =>
{
    def.DefaultAuthenticateScheme = Authenticators.Application;
    def.DefaultChallengeScheme = Authenticators.Application;
    def.DefaultScheme = Authenticators.Application;
})
.AddJwtBearer(Authenticators.Application, o =>
{
    o.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = configuration["Security:Issuer"],
        ValidAudience = configuration["Security:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Security:Key"])),
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true
    };
})

核心问题与解决方案

核心原因:编码方式不一致

令牌生成时使用Encoding.ASCII.GetBytes()转换密钥,而验证时使用Encoding.UTF8.GetBytes()。如果密钥包含ASCII范围(0-127)以外的字符,两种编码会生成不同的字节数组,直接导致签名验证失败。

修复步骤

统一两端的编码方式,推荐使用UTF-8(支持全字符集):

  1. 修改令牌生成端的密钥转换代码:
// 替换原ASCII编码为UTF8
var key = Encoding.UTF8.GetBytes(_settings.Value.Key);
  1. 确保验证端保持Encoding.UTF8.GetBytes()不变,或根据生成端调整为一致的编码。

额外排查点

如果修复编码后仍有问题,检查以下内容:

  • 确认Security:Issuer、Security:Audience、Security:Key在生成端和验证端的配置完全一致(包括大小写、空格、特殊字符)
  • 使用JWT解析工具查看令牌内容,检查exp(过期时间)是否有效,iss、aud是否与验证端配置匹配
  • 确保ASP.NET Core 8应用的中间件顺序正确:app.UseAuthentication()必须在app.UseAuthorization()之前注册

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:35:54