c# - 为什么我不能使用 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。
解决方案
将 SecurityAlgorithms.Sha256 更改为 SecurityAlgorithms.HmacSha256Signature
推荐阅读
- ios - 使用单例快速获取数据
- javascript - ServiceWorker:离线页面未显示
- php - 试图获取非对象 laravel 的属性“名称”
- javascript - 如何使用threejs使物体像浮力效果一样漂浮在水面上
- javascript - 使用 mixitup 手动删除元素
- javascript - 如何将 CSV 中的 http.get 响应转换为 JSON NodeJS
- sql - 当一个表为空时,查询在内部连接期间不返回任何内容
- javascript - 在 chart.js 文件中添加功能
- swift - dateComponents 试图以年为单位计算年龄的问题(swiftUI)
- sql - 从 SQL 服务器返回空结果集的简洁语法