[英]JWT Header algorithm: is "hs256" the same as "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"
I'm trying to sign a JWT using HS256.我正在尝试使用 HS256 签署 JWT。 I'm using System.IdentityModel.Tokens.Jwt
.我正在使用System.IdentityModel.Tokens.Jwt
。 When decoding the token using jwt.io
I get invalid signature and I've noticed that my headers read:使用jwt.io
解码令牌时,我得到无效签名,并且我注意到我的标头读取:
{
"alg": "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"typ": "JWT"
}
rather than {"alg":"HS256","typ":"JWT"}
as I expected.而不是我预期的{"alg":"HS256","typ":"JWT"}
。
Is this what's causing the invalid signature?这是导致无效签名的原因吗? Also any ideas on a fix?还有关于修复的任何想法? Please note that I need to include custom claims as well.请注意,我还需要包含自定义声明。
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);
You can create your JSON Web Token (JWT) as follows using System.IdentityModel.Tokens.Jwt, which should set all fields correctly ( secret
is the key you use to sign your JWT):您可以使用 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
finally contains the serialized JWT. serializedToken
最后包含序列化的 JWT。
Please note that the SecurityTokenDescriptor
class is from the Microsoft.IdentityModel.Tokens namespace of the same NuGet package , not from System.IdentityModel.Tokens namespace.请注意, SecurityTokenDescriptor
类来自 同一个 NuGet 包的 Microsoft.IdentityModel.Tokens 命名空间,而不是来自 System.IdentityModel.Tokens 命名空间。
SecurityAlgorithms.HmacSha256Signature SecurityAlgorithms.HmacSha256Signature
change改变
SecurityAlgorithms.HmacSha256安全算法.HmacSha256
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.