Search code examples
c#oauthjwtadfs3.0

How to decode a JWT using C# JWT Package with Signing Certificate


I am calling ADFS for getting an access token using OAuth Authorization Code Grant. I am getting an access token back in the form

{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dC...."
 "token_type":"bearer",
 "expires":3600}

Now, i am copying the access_token value and pasting it in https://jwt.io It decodes perfectly but with an Invalid Signature.

The Header for Jwt.io returns:

{
"typ": "JWT",
"alg": "RS256",
"x5t": "eQKi04zWoOV3eLmNNBrI2_rbqSY"
}

I have the pem token signing certificate that looks like:

-----BEGIN CERTIFICATE-----
MIIG0zCCBbugAwIBAgIKUJvNQgAAAAANxTA...
BgNVBAcTBEtlbnQxJjAkBgNVBAoTHVR...
-----END CERTIFICATE-----

Now, how to verify the token with the Certificate using System.IdentityModel.Tokens.Jwt or with any other method.

Kindly, help.


Solution

  • After a lot of research, i found the answer. Posting it here so it will be helpful to others.

      string token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1.."
      var tokenHandler = new JwtSecurityTokenHandler();
    //Read Token for Getting the User Details
      var parsedJwt = tokenHandler.ReadToken(token) as JwtSecurityToken; 
    
    //Create A Certificate Object that will read the .CER/.PEM/.CRT file as String
     X509Certificate2 clientCertificate = new X509Certificate2(Encoding.UTF8.GetBytes(CertficationString));
    
     var certToken = new X509SecurityToken(clientCertificate);
    
     var validationParameters = new TokenValidationParameters()
        {   
            IssuerSigningToken = certToken,
            ValidAudience = audience,
            ValidIssuer = issuer,
            ValidateLifetime = true,
            ValidateAudience = true,
            ValidateIssuer = true,
            ValidateIssuerSigningKey = true
        };
    
    
        try
        {
           SecurityToken validatedToken;
           var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
    
        }
        catch (Exception err)
        {
    
            Console.WriteLine("{0}\n {1}", err.Message, err.StackTrace);
        }