我正在尝试使用以下代码片段对我的JWt进行签名和编码:
var claims = new Claim[] { new SomeClaimes() };
var scKey = Encoding.UTF8.GetBytes("SOME KEY");
var ecKey = Encoding.UTF8.GetBytes("SOME OTHER KEY");
var tokenDescriptor = new SecurityTokenDescriptor {
Subject = new ClaimsIdentity(claims),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(
scKey),
SecurityAlgorithms.HmacSha512),
EncryptingCredentials = new EncryptingCredentials(
new SymmetricSecurityKey(
ecKey),
// I tryied all possible combination of algorithms here:
SecurityAlgorithms.XXXX,
SecurityAlgorithms.YYYY),
Issuer = "My Jwt Issuer",
Audience = "My Jwt Audience",
IssuedAt = DateTime.UtcNow,
Expires = DateTime.Now.AddDays(7),
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token);
但是当我运行代码时,出现错误:
加密失败。不支持:算法:“ {0}”,安全密钥:“ {1}”。
上面的代码中{0}
和{1}
是XXXX
和YYYY
的任意组合(是的,我编写了一个反射代码段,并尝试了所有可能的组合) )。哪些受支持的用于对签名的JWT进行编码(和解码)的算法?
答案 0 :(得分:0)
HmacSha512仅使用一个密钥来签名或验证令牌,请尝试使用RsaSha256之类的算法来对公钥/私钥进行加密。
答案 1 :(得分:0)
最后我找到了答案:
var claims = new Claim[] { new SomeClaimes() };
var scKey = Encoding.UTF8.GetBytes("SOME KEY");
var ecKeyTemp = Encoding.UTF8.GetBytes("SOME OTHER KEY");
// Note that the ecKey should have 256 / 8 length:
byte[] ecKey = new byte[256 / 8];
Array.Copy(ecKeyTemp, ecKey, 256 / 8);
var tokenDescriptor = new SecurityTokenDescriptor {
Subject = new ClaimsIdentity(claims),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(
scKey),
SecurityAlgorithms.HmacSha512),
EncryptingCredentials = new EncryptingCredentials(
new SymmetricSecurityKey(
ecKey),
SecurityAlgorithms.Aes256KW,
SecurityAlgorithms.Aes256CbcHmacSha512),
Issuer = "My Jwt Issuer",
Audience = "My Jwt Audience",
IssuedAt = DateTime.UtcNow,
Expires = DateTime.Now.AddDays(7),
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token);
如您所见,使用SecurityAlgorithms.Aes256KW
作为密钥加密算法和SecurityAlgorithms.Aes256CbcHmacSha512
作为加密算法即可完成工作。请注意,用于加密算法的密钥的长度应为256 / 8
。