I try to create a JWT
in C#
with the Libary Microsoft.IdentityModel.Tokens
but the https://jwt.io/ always says that my signature is wrong. This is my following Code. My IJsonWebTokenModel
just got a List of Claim
. What is wrong with my Code and another question what is my private und my secret key and where do I get it from?
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;
}
}
}