Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate JWT Token using JWKS in Dot Net Core

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"
      }
   ]
}
like image 1000
Anandaraj Avatar asked Oct 29 '19 04:10

Anandaraj


1 Answers

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);
like image 79
Karol Berezicki Avatar answered Sep 18 '22 07:09

Karol Berezicki