Home > front end >  Validate Bearer token (azure ad) with MSAL
Validate Bearer token (azure ad) with MSAL

Time:12-22

I have a aspnet core 6 API and i need in my controller of API, validated the bearer token that with Microsoft Authentication Libraries (MSAL).

I want verify in token, for example, my tenant or clientId.

How i do this simple? I need add notation to verify, for example [AuthorizeMSAL]?

Or i need to call "https://graph.microsoft.com" to validate token?

Example my code:

I receive an exception

The provided value for scope offline_access openid profile is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).

CodePudding user response:

What you are looking for in here is the Microsoft Identity Platform , which does the job of handling Tokens and authorization in the Bakcend part ( .net web APIs ) . In here I will suppose you have read and done the required configuration on the Azure portal , client app registration , Api registration , and exposing API (via scope or app roles ) if not please refer to the following docs for that.

Then you will need to install Microsft.Identity.Web nuget package to be able to handle the token .In order to make use of the token you need to register the following authentication service to the container inside program.cs

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

At this point you should already have and AzureAd section in in your appsetting.json with details from you Azure AD configuration like mentioned below :

    {
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "Enter_the_Application_(client)_ID_here",
    "TenantId": "common",
    "Audience": "Enter_the_Application_ID_URI_here"
  },
}

If the configuration is done right in the Azure portal side and you have the correct credentials at your appsettings.json , you should be able to allow only authenticated users into a specific controller by adding the [Authorize] annotation above the controller definition.

You find here a link to the documentation mentioning all the steps , along with a sample that you can follow on . and this link contains more information about MSAL issued bearer token configuration and validation

CodePudding user response:

I tried to reproduce the same in my environment and got the same error as below:

enter image description here

The error usually occurs if the scope value is invalid while generating the token.

Note that, Client Credential Grant Type accepts scope with ./default or api://ClientId/.default only.

To resolve the error, use the parameters like below while generating the token:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
client_secret:ClientSecret
grant_type:client_credentials
scope:https://graph.microsoft.com/.default

Access token generated successfully like below:

enter image description here

To validate the Bearer token, use the below sample code in your _Startup.cs_ file as mentioned in this MsDoc:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(Configuration);
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
  var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
  options.Events.OnTokenValidated = async context =>
  {
       await existingOnTokenValidatedHandler(context);
            options.TokenValidationParameters.ValidIssuers = new[] { Issuers };
      options.TokenValidationParameters.ValidAudiences = new[] { valid};
  };
});

The Bearer token will be validated successfully like below:

enter image description here

  • Related