JWT Header 算法:"hs256" 与 "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256" 相同

JWT Header algorithm: is "hs256" the same as "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"

我正在尝试使用 HS256 签署 JWT。我正在使用 System.IdentityModel.Tokens.Jwt 。使用 jwt.io 解码令牌时,我得到 invalid signature 并且我注意到我的 headers 读取:

{
  "alg": "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
  "typ": "JWT"
}

而不是我预期的 {"alg":"HS256","typ":"JWT"}

这是导致签名无效的原因吗?还有关于修复的任何想法吗?请注意,我还需要包括自定义声明。

var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(clientsecret));
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var header = new JwtHeader(credentials);

您可以使用 System.IdentityModel.Tokens.Jwt 创建您的 JSON Web 令牌 (JWT),它应该正确设置所有字段(secret 是您用来签署 JWT 的密钥) :

var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
  Subject = new ClaimsIdentity(new[] { new Claim("sub", "customer") }),
  Issuer = "Who issued the token",
  Claims = new Dictionary<string, object>
  {
    ["email"] = Email, 
  },
  IssuedAt = now,
  NotBefore = now,
  Expires = now + TimeSpan.FromDays(1),
  SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var serializedToken = tokenHandler.WriteToken(token);

serializedToken 最终包含序列化的 JWT。

请注意 SecurityTokenDescriptorclass 来自 same NuGet package 的 Microsoft.IdentityModel.Tokens 命名空间,而不是 System.IdentityModel.Tokens 命名空间。

SecurityAlgorithms.HmacSha256Signature

改变

SecurityAlgorithms.HmacSha256