How to Validate Azure Ad Security Token

How to validate Azure AD security token?

There are two steps to verify the token. First, verify the signature of the token to ensure the token was issued by Azure Active Directory. Second, verify the claims in the token based on the business logic.

For example, we need to verify the iss and aud claim if you were developing a single tenant app. And you also need to verify the nbf to ensure the token is not expired. For more claims you can refer here.

Below description is from here about the detail of signature verifying. (Note: The example below uses the Azure AD v2 endpoint. You should use the endpoint that corresponds to the endpoint the client app is using.)

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 signing tokens (public key)

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

Then we can use the JwtSecurityTokenHandler to verify the token using the sample code below:

 public JwtSecurityToken Validate(string token)
{
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;

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;
}

And if you were using the OWIN components in your project, it is more easy to verify the token. We can use the code below to verify the token:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = ConfigurationManager.AppSettings["ida:Audience"],
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});

Then we can use the code below to verify the ‘scope’ in the token:

public IEnumerable<TodoItem> Get()
{
// user_impersonation is the default permission exposed by applications in AAD
if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value != "user_impersonation")
{
throw new HttpResponseException(new HttpResponseMessage {
StatusCode = HttpStatusCode.Unauthorized,
ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found"
});
}
...
}

And here is a code sample which protected the web API with Azure AD:

Protect a Web API using Bearer tokens from Azure AD

Azure AD check if auth token is valid

You can make use of Postman API to generate the token and you can find expiration time in the response along with token like below:

Sample Image

To validate the auth token, you can make use of JSON Web Tokens - jwt.io.

  • After generating the auth token, you can paste the token in the above link and decode it.
  • Usually, the decoded token has sections like below:
    • header: It includes alg which specifies the type of algorithm used to digitally sign the token.
    • payload: It includes information about audience, scopes, expiration details, app details etc.
    • verification signature: It includes the digital signature of the token that was generated by Azure AD’s private key.

To check the token expiration, you can find expires_in variable under payload section of decoded token.

Sample Image

You can check the below references to know more in detail:

Validate Azure Active Directory (AD) generated OAuth tokens (voitanos.io)

How to verify token in Azure Active Directory – tsmatz (wordpress.com)

What exact token validation is done by Microsoft.Identity.Web’s aspnet core middleware?

Microsoft.Identity.Web - The main package. Required by all apps that use Microsoft Identity Web

Microsoft recommends you use the Microsoft.Identity.Web NuGet package when developing a web API with ASP.NET Core.

It has lot of dependecies you can check the detailse from this Link

One of Dependecies is for .NetCoreApp3.1 is Microsoft.AspNetCore.Authentication.JwtBearer (>= 3.1.18)

The JwtBearer middleware, like the OpenID Connect middleware in web apps, validates the token based on the value of TokenValidationParameters. The token is decrypted as needed, the claims are extracted, and the signature is verified. The middleware then validates the token by checking for this data:

Audience: The token is targeted for the web API.

Sub: It was issued for an app that's allowed to call the web API.

Issuer: It was issued by a trusted security token service (STS).

Expiry: Its lifetime is in range.

Signature: It wasn't tampered with.

for more information you can follow this MS documention.

getting 401 error while trying to validate a azure token

Your Java code looks pretty correct. I would start with adding extra logging to your application properties file to see if that tells you anything, eg:

logging:
level:
org:
springframework:
security: DEBUG

Next I would use a JWT viewer to see if there is a nonce field in the JWT header of the access token. If so then it will fail validation - see this recent answer of mine for more info on exposing an API scope in Azure AD.

Finally, you could try another library temporarily and it may give you a better explanation of the cause. See this jose4j code for an example of library based verification. You could paste that into a small Java console app and run it with an Azure access token.

How to generate access token for testing with Azure AD

To get the access token from Azure AD to authenticate and authorize users from Azure AD.

  1. First, you need to register both the application mobile client and spring boot applications in your Azure AD. Refer register your application in the Azure AD.

  2. To generate access token using client credentials flow, there would be no user involvement, so your server application needs to create an appRole, and then grant the app Role as an application permission to the client application.
    The administrator must grant the correct application permissions via a consent process to access the application.

  3. Configure the application's details registered in Azure AD to your spring boot application.properties file with application id, tenant id, client-secret and scope.

  4. Refer guide to configure client application to access a web API using spring boot step by step.



Related Topics



Leave a reply



Submit