[Office 365 Dev] How to Validate the Access Token Issued by Microsoft Azure AD

By following the document Authorization Code Grant Flow, we can get the access token to access the declared resources.

This article will introduce how is the access token being validated on the Resource Web API side.

web-resource-api

The access token from the Azure AD is a JSON Web Token(JWT) which is signed by Security Token Service in private key.

The JWT includes 3 parts: header, data and signature. Technically, we can use the public key to validate the access token.

First step – retrieve and cache the singing tokens (public key)

Endpoint: https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration open-connectid-config

Code:

 string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";

ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);

OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;

 

Second step – validate the token via JwtSecurityTokenHandler

Code:

 TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidateIssuer = false,
                IssuerSigningTokens = config.SigningTokens,
                ValidateLifetime = false
            };

JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();

SecurityToken jwt;

            var result = tokendHandler.ValidateToken(token, validationParameters, out jwt);

return jwt as JwtSecurityToken;

Complete code on GitHub: https://github.com/dream-365/OfficeDev-Samples/blob/master/samples/Office365DevQuickStart/OAuth2-basic/JsonWebTokenValidator.cs