跳到主要内容
ecdsa.com
Microsoft.IdentityModel.JsonWebTokens / System.IdentityModel.Tokens.Jwt (.NET).NET

错误信息

IDX10511: Signature validation failed. Keys tried:

也可能输出为

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

消息的其余部分列出了尝试过的密钥(除非开启 `ShowPII`,否则显示为 `[PII … is hidden]`)、密钥数量、匹配密钥的来源以及 `kid`。

Microsoft.IdentityModel.JsonWebTokens / System.IdentityModel.Tokens.Jwt (.NET) — SecurityTokenInvalidSignatureException

含义

与 IDX10503 不同,这里找到了与令牌 `kid` 对应的密钥(“Matched key was in 'TokenValidationParameters'”或“…'Configuration'”)——但用它验证签名仍然失败。要么是两个不同的密钥共用了一个密钥 ID,要么是令牌在签名后被改动过。ASP.NET Core 的响应是 `error_description="The signature is invalid"`。

原因

修复方法

  1. 1.

    使用基于指纹的密钥 ID

    由密钥材料计算出的 `kid`(RFC 7638)只有在密钥完全相同时才会冲突。

    csharp
    // Derive kid from the key itself (RFC 7638 thumbprint) so different keys never share an ID.
    var jwk = JsonWebKeyConverter.ConvertFromECDsaSecurityKey(new ECDsaSecurityKey(ecdsa));
    var key = new ECDsaSecurityKey(ecdsa) { KeyId = Base64UrlEncoder.Encode(jwk.ComputeJwkThumbprint()) };
  2. 2.

    约定一致的密钥字节

    以 base64 编码存储共享密钥,并在两端用相同的方式解码。

    csharp
    // HS256: issuer and API must build the key from the same bytes.
    var secret = Convert.FromBase64String(builder.Configuration["Jwt:SecretBase64"]!); // >= 32 bytes
    var signingKey = new SymmetricSecurityKey(secret);

相关错误

浏览完整的签名错误库