[SOLVED] Azure AD B2C code example does not provide token validation option

Issue

I understand that Microsoft emphasizes on a proper token validation.

The following code example (link includes the exact line of code) does not include token validation:

https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/blob/master/4-WebApp-your-API/4-2-B2C/Client/Startup.cs#L44

            services.AddMicrosoftIdentityWebAppAuthentication(Configuration, Constants.AzureAdB2C)
                    .EnableTokenAcquisitionToCallDownstreamApi(new string[] { Configuration["TodoList:TodoListScope"] })
                    .AddInMemoryTokenCaches();

How can I improve above line of code so that it can validate tenant ID claim?

Solution

• To validate the token received from Azure AD B2C in Asp.Net, you will have to include ‘TokenValidationParameters’ value and define the validation of token claims received accordingly in the ‘Startup.cs’ file of the Web API. Please find the below sample code to be included in the ‘Startup.cs’ file for token validation which protects the Web API with Microsoft Identity platform: –

   services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
      .AddMicrosoftIdentityWebApi(options =>
   {
        Configuration.Bind("AzureAdB2C", options);
      options.TokenValidationParameters.ValidIssuers = new[] { /* list of valid issuers */ };
      options.TokenValidationParameters.ValidAudiences = new[] { /* list of valid audiences */};
   },
       options => { Configuration.Bind("AzureAdB2C", options); });

Once the above has been done, add the method app.UseAuthentication() before app.UseMvc() in the Configure method as below: –

 ‘ app.UseAuthentication();
   app.UseMvc(); ‘

Thus, you can add token validation parameters in your Asp.Net Web API for verifying tenant ID claims. For more detailed information regarding this, please refer to the documentation links below: –

https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/4-WebApp-your-API/4-2-B2C

https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-app-configuration#token-validation

Answered By – KartikBhiwapurkar-MT

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *