Ok, I understand that the question I am asking may be pretty obvious, but unfortunately I lack the knowledge on this subject and this task seems to be quite tricky for me.>
For anyone that is looking for a quick method to validate RS256 with a public key that has "-----BEGIN PUBLIC KEY-----"/"-----END PUBLIC KEY------"
Here are two methods with the help of BouncyCastle.
public bool ValidateJasonWebToken(string fullKey, string jwtToken)
{
try
{
var rs256Token = fullKey.Replace("-----BEGIN PUBLIC KEY-----", "");
rs256Token = rs256Token.Replace("-----END PUBLIC KEY-----", "");
rs256Token = rs256Token.Replace("\n", "");
Validate(jwtToken, rs256Token);
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
}
private void Validate(string token, string key)
{
var keyBytes = Convert.FromBase64String(key); // your key here
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters
{
Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned()
};
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(rsaParameters);
var validationParameters = new TokenValidationParameters()
{
RequireExpirationTime = false,
RequireSignedTokens = true,
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKey = new RsaSecurityKey(rsa)
};
var handler = new JwtSecurityTokenHandler();
var result = handler.ValidateToken(token, validationParameters, out var validatedToken);
}
}
This is a combination of http://codingstill.com/2016/01/verify-jwt-token-signed-with-rs256-using-the-public-key/ and @olaf answer that uses system.IdentityModel.Tokens.Jwt