我尝试使用JWT
在C#
中创建一个Libary Microsoft.IdentityModel.Tokens
,但是https://jwt.io/总是说我的签名是错误的。这是我的以下代码。我的IJsonWebTokenModel
刚得到一个List of Claim
。我的代码有什么问题,还有另一个问题,我的私钥和秘密密钥是什么,我从哪里得到它?
public string GenerateToken(IJsonWebTokenModel model)
{
if (model == null || model.Claims == null || !model.Claims.Any())
throw new ArgumentException("Arguments to create token are not valid.");
IdentityModelEventSource.ShowPII = true;
SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(model.Claims),
Expires = model.ExpiresAt,
SigningCredentials = new SigningCredentials(GetPublicKey(), SecurityAlgorithms.RsaSha256Signature),
//EncryptingCredentials = new EncryptingCredentials(GetPublicKey(), SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes128CbcHmacSha256)
};
JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
var jweAymmetric = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
string token = jwtSecurityTokenHandler.WriteToken(jweAymmetric);
return token;
}
private SecurityKey GetPublicKey()
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
try
{
RSAParameters rsaKeyInfo = rsa.ExportParameters(true);
var key = new RsaSecurityKey(rsaKeyInfo);
return key;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}