How to properly consume OpenID Connect jwks_uri metadata in C#?

Rob L picture Rob L · Nov 5, 2017 · Viewed 9.7k times · Source

Per the OpenID Connect specification, providers can publish a discovery document that includes a jwks_uri property. The data returned from the jwks_uri seems to take on two different forms. One form contains fields called x5c and x5t. An example of this looks like:

{
    "keys": [
        {
            "kty": "RSA",
            "use": "sig",
            "kid": "C61F8F2524D080D0DB0A508747A94C2161DEDAC8",
            "x5t": "xh-PJSTQgNDbClCHR6lMIWHe2sg", <------ HERE
            "e": "AQAB",
            "n": "lueb...",
            "x5c": [
                "MIIC/..." <------ HERE
            ],
            "alg": "RS256"
        }
    ]
}

The other version that I see omits the x5c and x5t properties but contains e and n. An example of this is:

{
    "keys": [
        {
            "kty": "RSA",
            "alg": "RS256",
            "use": "sig",
            "kid": "cb11e2f233aee0329a5344570349cddb6b8ff252",
            "n": "sJ46h...", <------ HERE
            "e": "AQAB"      <------ HERE
        }
    ]
}

I don't quite understand what the difference is and why sometimes an x5c/x5t combination is used but other times it is simply e/n. I am using C#'s Microsoft.IdentityModel.Tokens.TokenValidationParameters and I am trying to figure out how to supply the property IssuerSigningKey. A sample usage of this class is

new TokenValidationParameters
{
    ValidateAudience = true,
    ValidateIssuer = true,
    ...,
    IssuerSigningKey = new X509SecurityKey(???) or new JsonWebKey(???) //How to create this based on x5c/x5t and also how to create this based on e and n ?
}

Given the two different JWK metadata formats how do I use them to provide the IssuerSigningKey to the TokenValidationParameter so I can validate access tokens?

Answer

Rob L picture Rob L · Nov 20, 2017

This is what I ended up going with:

//Model the JSON Web Key Set
public class JsonWebKeySet
{
     [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "keys", Required = Required.Default)]
     public JsonWebKey[] Keys { get; set; }
}


//Model the JSON Web Key object
public class JsonWebKey
{
    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "kty", Required = Required.Default)]
    public string Kty { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "use", Required = Required.Default)]
    public string Use { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "kid", Required = Required.Default)]
    public string Kid { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "x5t", Required = Required.Default)]
    public string X5T { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "e", Required = Required.Default)]
    public string E { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "n", Required = Required.Default)]
    public string N { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "x5c", Required = Required.Default)]
    public string[] X5C { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = "alg", Required = Required.Default)]
    public string Alg { get; set; }
}

I first make a request to the jwks_uri endpoint which is provided in the OpenID Connect discovery document. The request will populate the above objects accordingly. I then pass the JsonWebKeySet object to a method that creates a ClaimsPrincipal

string idToken = "<the id_token that was returned from the Token endpoint>";
List<SecurityKey> keys = this.GetSecurityKeys(jsonWebKeySet);
var parameters = new TokenValidationParameters
                 {
                      ValidateAudience = true,
                      ValidAudience = tokenValidationParams.Audience,
                      ValidateIssuer = true,
                      ValidIssuer = tokenValidationParams.Issuer,
                      ValidateIssuerSigningKey = true,
                      IssuerSigningKeys = keys,
                      NameClaimType = NameClaimType,
                      RoleClaimType = RoleClaimType
                  };

 var handler = new JwtSecurityTokenHandler();
 handler.InboundClaimTypeMap.Clear();

 SecurityToken jwt;
 ClaimsPrincipal claimsPrincipal = handler.ValidateToken(idToken, parameters, out jwt);

 // validate nonce
 var nonceClaim = claimsPrincipal.FindFirst("nonce")?.Value ?? string.Empty;

 if (!string.Equals(nonceClaim, "<add nonce value here>", StringComparison.Ordinal))
 {
      throw new AuthException("An error occurred during the authentication process - invalid nonce parameter");
 }

 return claimsPrincipal;

The GetSecurityKeys method is implemented like so

private List<SecurityKey> GetSecurityKeys(JsonWebKeySet jsonWebKeySet)
{
      var keys = new List<SecurityKey>();

      foreach (var key in jsonWebKeySet.Keys)
      {
          if (key.Kty == OpenIdConnectConstants.Rsa)
          {
             if (key.X5C != null && key.X5C.Length > 0)
             {
                string certificateString = key.X5C[0];
                var certificate = new X509Certificate2(Convert.FromBase64String(certificateString));

                var x509SecurityKey = new X509SecurityKey(certificate)
                                      {
                                          KeyId = key.Kid
                                      };

                 keys.Add(x509SecurityKey);
              }
              else if (!string.IsNullOrWhiteSpace(key.E) && !string.IsNullOrWhiteSpace(key.N))
              {
                  byte[] exponent = Base64UrlUtility.Decode(key.E);
                  byte[] modulus = Base64UrlUtility.Decode(key.N);

                  var rsaParameters = new RSAParameters
                                      {
                                          Exponent = exponent,
                                          Modulus = modulus
                                      };

                  var rsaSecurityKey = new RsaSecurityKey(rsaParameters)
                                       {
                                           KeyId = key.Kid
                                       };

                  keys.Add(rsaSecurityKey);
              }
              else
              {
                  throw new PlatformAuthException("JWK data is missing in token validation");
              }
          }
          else
          {
              throw new NotImplementedException("Only RSA key type is implemented for token validation");
          }
      }

      return keys;
  }