Reputation: 57482
I'm using Auth0 and parsing its idToken
server-side like this:
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadJwtToken(idToken); // idToken comes from client using auth0.js
var sub = jwtToken.Claims.First(claim => claim.Type == "sub").Value;
The above code works well and I'm able to parse the idToken
successfully, but I'd like to validate the idToken
before trusting it, so I've tried this:
string clientSecret = "{client_secret}"; // comes from Auth0 application's client secret
var validations = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "some value", // used "iss" from here: https://jwt.io/
ValidAudience = "some value", // used "aud" from here: https://jwt.io/
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(clientSecret)),
};
var principal = tokenHandler.ValidateToken(idToken, validations, out var validatedToken);
When trying to validate the token, it results in this exception:
Microsoft.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException
HResult=0x80131500
Message=IDX10501: Signature validation failed. Unable to match key:
kid: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'
I grabbed the issuer and audience values by parsing one of the tokens here: https://jwt.io/. The client secret is my application's client secret at Auth0.
How can I validate Auth0's idToken
using JwtSecurityTokenHandler
?
Upvotes: 1
Views: 2754
Reputation: 57482
To manually validate Auth0's JWT token, you need these 2 Nuget packages:
System.IdentityModel.Tokens.Jwt
Microsoft.IdentityModel.Protocols.OpenIdConnect
Then get these values from Auth0's application settings
string auth0Domain = ""; // Note: if your Domain is foo.auth0.com, this needs to be https://foo.auth0.com/
string auth0ClientId = "";
Validate Auth0's token as follows:
IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{auth0Domain}.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
OpenIdConnectConfiguration openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);
var validations = new TokenValidationParameters
{
ValidIssuer = auth0Domain,
ValidAudiences = new[] { auth0ClientId },
IssuerSigningKeys = openIdConfig.SigningKeys
};
var user = tokenHandler.ValidateToken(idToken, validations, out var validatedToken);
With the validated token, you can extract useful info like this:
var securityToken = (JwtSecurityToken)validatedToken;
var userId = user.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value;
Source: Manually validating a JWT using .NET
Credit: @Nkosi
Upvotes: 1