我正在尝试使用以下代码段对我的 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}
是上面代码中 XXXX
和 YYYY
的任意组合(是的,我写了一个反射片段并尝试了所有可能的组合)。哪些是用于编码(和解码)签名 JWT 的受支持算法? 最佳答案
最后我找到了答案:
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
作为 key 加密算法并使用 SecurityAlgorithms.Aes256CbcHmacSha512
作为加密算法就可以完成这项工作。请注意,用于加密算法的 key 应具有 256 / 8
长度。关于c# - 加密 JWT 安全 token 支持的算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53487247/