Home » Web API » Validate Azure Active Directory B2C Jwt Bearer Token in .NET Core Web API – C#

Validate Azure Active Directory B2C Jwt Bearer Token in .NET Core Web API – C#

To validate a JSON Web Token (JWT) issued by Azure Active Directory B2C (Azure AD B2C) in a .NET Core Web API, you need to configure the authentication middleware to validate the JWT tokens.


Steps to Validate Azure AD B2C Jwt Bearer


Create Web API project in .NET Core

Install Required NuGet Packages

Install the necessary JwtBearer NuGet packages to work with JWT authentication and Azure AD B2C.

microsoft aspnetcore authentication jwtbearer nuget validate b2c Azure token


Configure Azure B2C JWT Authentication.

In your Startup.cs file, configure JWT authentication in the ConfigureServices and Configure methods:

Startup.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

// ...

public void ConfigureServices(IServiceCollection services)
{
	// Add authentication services
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
			options.Authority = "AzureAdB2C:IssuerOrAuthorizationUrl";
			options.Audience = "AzureAdB2C:Audience";
			options.Events = new JwtBearerEvents
			{
				//OnAuthenticationFailed = AuthenticationFailed
			};
			
			/* Note:Authority and audience are enough to validate AD B2C Authentication but if your requirement is to validate the Token issuer & SigninKey also then include the below code as well.*/
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                //ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "AzureAdB2C:IssuerOrAuthorizationUrl",
                ValidAudience = "AzureAdB2C:Audience",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AzureAdB2C:JwtKey"]))
            };
        });

    // Other ConfigureServices configuration...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Use authentication middleware
    app.UseAuthentication();

    // Other Configure configuration...
} 

appsettings.json
{
  "AzureAdB2C": {
    "IssuerOrAuthorizationUrl": "https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/<your-policy-name>/v2.0/",
    "Audience": "ecjud59-Your-ClientId-or-AudienceId-e0d02e",
    "JwtKey": "my_secret_key_12345"
  }
}


Note:
In my scenario, I had two web API apps for the same client, where in
app1: “Authority & Audience” was enough to validate B2C Authentication and
app2: I used the “TokenValidationParameters” code to verify “IssuerSigningKey”.
So based on your requirement include or remove the lines of code.


Authorize API Endpoints

You can now protect your API endpoints by applying the [Authorize] attribute to the controllers or actions you want to secure:

using Microsoft.AspNetCore.Authorization;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
    // Controller actions...
}

Your .NET Core rest API is now configured to validate JWT tokens issued by Azure AD B2C.


Testing Azure AD B2C Jwt Bearer

To test the JWT Bearer token authentication, include the JWT token in the Authorization header of your HTTP requests. The header should look like:

Authorization: Bearer <your-JWT-token>

If validation is successful then it will execute the API method else app will throw an exception.


Make sure you have the correct Azure AD B2C configuration values in your application, and ensure that your B2C policies and user flows are set up to issue tokens with the required audience and issuer values.

Handle Claims: You can access user claims (e.g., user’s email, name, etc.) using User.Claims within your API controller actions.



Leave a Reply

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