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:
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: –
Answered By – KartikBhiwapurkar-MT
Answer Checked By – Willingham (BugsFixing Volunteer)