我一直在尝试使用简单的密钥创建和签署JwtSecurityToken.经过大量研究后,我发现所有示例似乎都使用InMemorySymmetricSecurityKey类,但不幸的是,这个类似乎不存在于最新版本的System.IdentityModel库中.
这些是我正在使用的依赖项:
"System.IdentityModel.Tokens": "5.0.0-rc1-211161024",
"System.IdentityModel.Tokens.Jwt": "5.0.0-rc1-211161024"
Run Code Online (Sandbox Code Playgroud)
我也尝试使用它的基类SymmetricSecurityKey但是在尝试创建令牌时我得到以下异常:
"Value cannot be null.\r\nParameter name: IDX10000: The parameter 'signatureProvider' cannot be a 'null' or an empty object."
Run Code Online (Sandbox Code Playgroud)
这是抛出异常的代码:
public static string CreateTokenHMAC()
{
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String("test"));
var key = new SymmetricSecurityKey(hmac.Key);
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
JwtSecurityToken token = _tokenHandler.CreateJwtSecurityToken(new SecurityTokenDescriptor()
{
Audience = AUDIENCE,
Issuer = ISSUER,
Expires = DateTime.UtcNow.AddHours(6),
NotBefore = DateTime.Now,
Claims = new List<Claim>()
{
new Claim(ClaimTypes.Email, "johndoe@example.com")
},
SigningCredentials …Run Code Online (Sandbox Code Playgroud)