Monday, August 15, 2016

OAuth2 : Verifying the Azure AD JWT signature

Was having a look at Azure AD and JWT tokens and was wondering how the signature was calculated?

I use this useful utility from Auth0 to decode the tokens.

So I paste either the access or identity token into the "Encoded" box and set the "Algorithm" drop down to "RS256" (as below in bold). Problem is the signature is invalid. So how do I verify it.?

Looking at a typical token header,

{
  "typ": "JWT",
  "alg": "RS256",
  "kid": "MnC_VZcATfM5pOYiJHMba9goEKY"
}


we see the algorithm and the reference to the public key.

In Azure AD, we can get the OAuth 2.0 details from the discovery endpoint viz.



and that gives us:

"authorization_endpoint": "https://login.microsoftonline.com/common/oauth2/
    authorize",
    "token_endpoint": "https://login.microsoftonline.com/common/oauth2/token",
    "token_endpoint_auth_methods_supported": [
        "client_secret_post",
        "private_key_jwt"
    ],
    "jwks_uri": "https://login.microsoftonline.com/common/discovery/keys",
    "response_modes_supported": [
        "query",
        "fragment",
        "form_post"
    ],
... 

Now if we go to the key endpoint (bold above), we see:

"keys": [
        {
            "kty": "RSA",
            "use": "sig",
            "kid": "MnC_VZcATfM5pOYiJHMba9goEKY",
            "x5t": "MnC_VZcATfM5pOYiJHMba9goEKY",
            "n": "vIqz-4-ER_vNWLON9yv8hIYV737...NOhfXgelixLUQ",
            "e": "AQAB",
            "x5c": [
                "MIIC4jCCAc...H3/bKkLSuDaKLWSqMhozdhXsIIKvJQ=="
            ]
        },
... 

There is  more than one of these sets. You need the one whose "kid" matches the "kid" in the JWT header.

The "x5c" is the public key. Copy the entire string e.g. from "MIIC" to "JQ==" in the above to Notepad.

Now add:

"-----BEGIN CERTIFICATE-----"

at the beginning and add:

"-----END CERTIFICATE-----"

at the end.

You should have something like:

-----BEGIN CERTIFICATE-----
MIIC4jCCAc
...
H3/bKkLSuDaKLWSqMhozdhXsIIKvJQ==
-----END CERTIFICATE-----

Now paste that into the "Verify Signature" box and you'll see the "Signature Verified" message at the bottom in blue.

Enjoy!

No comments: