Introduction

Have you ever wanted to add Azure AD authentication to a C# WebApi project for .NET 8?

Now you can.

The Code

First, let’s create a new WebAPI project:

dotnet new webapi --use-controllers

Next, add the required package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Next, we need to add the Azure AD settings in appsettings.json:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "TenantId": "yyyy",
  "ClientId": "xxxxx"
}

Replace yyyy with the correct TenantId and xxxxx with the correct Azure SPN Client Id.

Add the JWT authentication to program.cs similar to this:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    //.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
    .AddJwtBearer(opt =>
    {
        opt.Authority = $"{builder.Configuration["AzureAd:Instance"]}{builder.Configuration["AzureAd:TenantId"]}";
        opt.Audience = $"api://{builder.Configuration["AzureAd:ClientId"]}";
        opt.IncludeErrorDetails = true;
    });

Unfortunately, I could not get the AddMicrosoftIdentityWebApi version of the code working.

In order to add Bearer authentication to Swagger, update the builder.Services.AddSwaggerGen() with the following code:

builder.Services.AddSwaggerGen(opt =>
{
    opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "Please enter token",
        Name = "Authorization",
        Type = SecuritySchemeType.Http,
        BearerFormat = "JWT",
        Scheme = "bearer"
    });
 
    opt.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type=ReferenceType.SecurityScheme,
                    Id="Bearer"
                }
            },
            new string[]{}
        }
    });
});

Finally, add [Authorize] to your controllers.

Running it

If everything is ok, then run the WebAPI project using:

dotnet run

Next, get a Bearer token using Postman (or curl):

1-postman-auth

Now you can call the WebAPI service:

2-webapi-call