[英]Why can't I create a jwt token with SHA256?
我第一次实现基于 JWT 的身份验证,并基于我在网上找到的一些资源实现。 我想知道,我对 jwt 的秘密定义为:
"JwtConfig": {
"secret": "pma_secret_2019_2020",
"durationInMinutes": 1440,
"issuer": "localhost:5001"
}
现在我对这段代码有疑问:
var symmetricKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_secret)
);
var signinCredentials =
new SigningCredentials(symmetricKey, SecurityAlgorithms.Sha256);
var expirationDate = DateTime.Now.AddMinutes(_durationInMinutes);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = expirationDate,
SigningCredentials = signinCredentials
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
create Token 抛出以下异常:
System.NotSupportedException: IDX10634: Unable to create the SignatureProvider.
Algorithm: 'System.String', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey'
is not supported.
有人可以解释为什么我不断收到此错误吗? 它与秘密的大小或其字符或其他什么有关吗?
该代码在算法更改为 HmacSHA256 时有效。 但我想了解为什么它不适用于 SHA256。
将 SecurityAlgorithms.Sha256 更改为 SecurityAlgorithms.HmacSha256Signature
SHA256 只是一种散列算法,它不提供签名机制。 这就是为什么HMAC是正确的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.