In C#, I need to validate the Bearer Token against the JWKS (Json object which represent the set of keys like below)
{
"keys":[
{
"e":"AQAB",
"kid":"unique key",
"kty":"RSA",
"n":"some value"
}
]
}
You can do this using Microsoft's Nuget packages Microsoft.IdentityModel.Tokens
and System.IdentityModel.Tokens.Jwt
Use following code to create token validator:
private static bool ValidateToken(string token, TokenValidationParameters validationParameters)
{
var tokenHandler = new JwtSecurityTokenHandler();
try
{
tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
return validatedToken != null;
}
catch (Exception)
{
return false;
}
}
And for usage you have to load JWKS and select a key for validation parameters:
var jwksJson = @"
{
""keys"":[
{
""e"":""AQAB"",
""kid"":""unique key"",
""kty"":""RSA"",
""n"":""some value""
}
]
}";
var token = "eyJhb...";
var jwks = new JsonWebKeySet(jwksJson);
var jwk = jwks.Keys.First();
var validationParameters = new TokenValidationParameters
{
IssuerSigningKey = jwk,
ValidAudience = "", // Your API Audience, can be disabled via ValidateAudience = false
ValidIssuer = "" // Your token issuer, can be disabled via ValidateIssuer = false
};
var isValid = ValidateToken(token, validationParameters);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With