首页 > 解决方案 > 为什么我不能使用 SHA256 创建 jwt 令牌?

问题描述

我是第一次实现基于 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。

标签: c#.netasp.net-coreasp.net-core-3.0

解决方案


将 SecurityAlgorithms.Sha256 更改为 SecurityAlgorithms.HmacSha256Signature


推荐阅读