9

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"
      }
   ]
}
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
Anandaraj
  • 91
  • 1
  • 1
  • 3

1 Answers1

17

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);
Karol Berezicki
  • 652
  • 1
  • 8
  • 14
  • 1
    What if you don't want to use the first key - what if you want to check if any of them are matching by kid? – th3morg Feb 28 '20 at 19:26
  • 1
    @th3morg You could create multiple `TokenValidationParameters` and validate each of them or you could select `JsonWebKey` by `KeyId` property. – Karol Berezicki Feb 28 '20 at 19:50
  • Just for anyone else with the same question as @th3morg - see https://stackoverflow.com/a/64274938/419934 which shows you how to get the key list into the correct format which can then be used to set the IssuerSigningKeys in the TokenValidationParameters field. – Mike Jan 08 '22 at 16:28