I'm generating and validating a JWT with the following code.
static string GenerateToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
var certificate = new X509Certificate2(@"Test.pfx", "123");
var rsa = certificate.GetRSAPrivateKey();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(),
Issuer = "Self",
IssuedAt = DateTime.Now,
Audience = "Others",
Expires = DateTime.MaxValue,
SigningCredentials = new SigningCredentials(
new RsaSecurityKey(rsa),
SecurityAlgorithms.RsaSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
static bool ValidateToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var certificate = new X509Certificate2(@"Test.cer");
var rsa = certificate.GetRSAPublicKey();
var validationParameters = new TokenValidationParameters
{
ValidAudience = "Others",
ValidIssuer = "Self",
IssuerSigningKey = new RsaSecurityKey(rsa)
};
var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken securityToken);
if (principal == null)
return false;
if (securityToken == null)
return false;
return true;
}
I have this code in a library which targets .net standard 2.0 and net46.
When I use the library in an .net core app 2.0 project everything is working as expected. I use the following nuget packages.
- System.IdentityModel.Tokens.Jwt => 5.1.4
- System.Security.Cryptography.Csp => 4.3.0
But when I build the same code with .net46 I get the following exception when trying to generate a token.
var token = tokenHandler.CreateToken(tokenDescriptor);
System.NotSupportedException: 'NotSupported_Method'
The the following exception is throw when I try to validate a token.
var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken securityToken);
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: 'IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.RsaSecurityKey , KeyId: '.