我可以使用此点网核心2.2代码使用HmacSha256算法创建对称签名的jwt令牌。
using System;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var securityKey = "7iMdnuwf7XMMKGXGSMHKcs+qicGCinCJONLPrhGOX94=";
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(securityKey));
var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(signingCredentials: signingCredentials);
Console.WriteLine(new JwtSecurityTokenHandler().WriteToken(token));
}
}
}
但是如果我将算法更改为Aes128CbcHmacSha256,则会出现此异常。
System.InvalidOperationException
HResult=0x80131509
Message=IDX10677: GetKeyedHashAlgorithm threw, key: [PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.], algorithm [PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.].
Source=Microsoft.IdentityModel.Tokens
StackTrace:
at Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider.get_KeyedHashAlgorithm()
at Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider.Sign(Byte[] input)
at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
at ConsoleApp1.Program.Main(String[] args) in D:\Users\d841616\source\repos\JwtTokenTest\ConsoleApp1\Program.cs:line 16
Inner Exception 1:
InvalidOperationException: IDX10677: GetKeyedHashAlgorithm threw, key: [PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.], algorithm [PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.].
Inner Exception 2:
NotSupportedException: IDX10666: Unable to create KeyedHashAlgorithm for algorithm '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
谁能解释为什么这失败了?
答案 0 :(得分:0)
使用Aes128CbcHmacSha256时,需要提供第二个密钥来加密jwt内容。
static void Main(string[] args)
{
var securityKey = "7iMdnuwf7XMMKGXGSMHKcs+qicGCinCJONLPrhGOX94=";
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(securityKey));
var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
var encryptingKey = "7iMdnuwf7XMMKGXG";
var symmetricEncryptingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(encryptingKey));
var encryptingCredentials = new EncryptingCredentials(symmetricEncryptingKey, SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);
var handler = new JwtSecurityTokenHandler();
var claims = new List<Claim>()
{
new Claim("group", "test"),
};
var jwtSecurityToken = handler.CreateJwtSecurityToken(
"issuer",
"Audience",
new ClaimsIdentity(claims),
DateTime.Now,
DateTime.Now.AddHours(1),
DateTime.Now,
signingCredentials,
encryptingCredentials);
string tokenString = handler.WriteToken(jwtSecurityToken);
Console.WriteLine(tokenString);
Console.ReadLine();
}
}