liveBook · Manning

JWT Authentication

As explained in ASP.NET Core in Action, 3e

JWT bearer authentication is an HTTP authentication technique that presents and validates a signed JSON Web Token in a bearer authorization header.

JWT bearer authentication protects an ASP.NET Core API by validating a JSON Web Token supplied in the bearer authorization header. A minimal API can require authentication for selected endpoints, returning 401 Unauthorized when a request lacks a valid token. section 25.3 section 25.5

A minimal API setup follows these steps:

  • Install Microsoft.AspNetCore.Authentication.JwtBearer. section 25.3
  • Register authentication with AddAuthentication().AddJwtBearer() and register authorization with AddAuthorization(). section 25.3
  • Add UseAuthentication() and UseAuthorization() to the middleware pipeline when controlling their position explicitly. section 25.3
  • Protect an endpoint with RequireAuthorization(), which requires the request to be authenticated. section 25.3

Protecting a recipe endpoint

After JWT authentication and authorization are registered, map GET /recipe and append RequireAuthorization(). Requests without a token receive a 401 Unauthorized challenge; authenticated requests can reach the endpoint. section 25.3

Listing 25.1 Adding JWT bearer authentication to a minimal API application
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddAuthentication()         #1
    .AddJwtBearer();                         #2
builder.Services.AddAuthorization();         #3
 
builder.Services.AddScoped<RecipeService>();
 
WebApplication app = builder.Build();
 
app.UseAuthentication();                     #4
app.UseAuthorization();                      #5
 
app.MapGet("/recipe", async (RecipeService service) =>
{
    return await service.GetRecipes();
}).RequireAuthorization();                   #6
 
app.Run();
#1 Adds the core authentication services
#2 Adds and configures JWT authentication
#3 Adds the core authorization services
#4 Adds the authentication middleware
#5 Adds the authorization middleware
#6 Adds an authorization policy to the minimal API endpoint

Inspect the complete minimal API configuration, including service registration, middleware, and endpoint protection. section 25.3

Listing 25.2 Adding bearer authentication to an OpenAPI document using Swashbuckle
WebApplicationBuilder = WebApplication.CreateBuilder(args);
 
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
 
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(x =>
{
    x.SwaggerDoc("v1", new OpenApiInfo {
        Title = "Recipe App", Version = "v1" });
 
var security = new OpenApiSecurityScheme                     #1
  {
        Name = HeaderNames.Authorization,                        #2
        Type = SecuritySchemeType.ApiKey,                        #3
        In = ParameterLocation.Header,                           #4
        Description = "JWT Authorization header",                #5
        Reference = new OpenApiReference
        {
            Id = JwtBearerDefaults.AuthenticationScheme,         #6
            Type = ReferenceType.SecurityScheme                  #7
        }
    };
 
    x.AddSecurityDefinition(security.Reference.Id, security);    #8
    x.AddSecurityRequirement(new OpenApiSecurityRequirement      #9
        {{security, Array.Empty<string>()}});                    #9
});
 
var app = builder.Build();
 
 
app.UseSwagger();
app.UseSwaggerUI();
 
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
 
app.MapGet("/", () => "Hello world!").RequireAuthorization();
app.Run();
#1 Defines the security used by your API
#2 The name of the header to use (required)
#3 The type of security; may be OAuth2 or OpenIdConnect if using those (required)
#4 Where the token will be provided (required)
#5 A friendly description of the scheme, used in the UI
#6 A unique ID for the scheme. This uses the default JWT scheme name.
#7 The type of OpenID object (required)
#8 Adds the security definition to the OpenAPI document
#9 Marks the whole API as protected by the security definition

Use the OpenAPI configuration to describe bearer authentication to Swagger UI. section 25.5

Swagger UI can expose an Authorize button when the OpenAPI document defines a bearer security scheme and applies it to the API or selected endpoints. Enter Bearer <token>, including the space and prefix; Swagger UI then sends the token in the Authorization header. section 25.5

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains package setup, service registration, middleware, endpoint policies, and OpenAPI testing, but does not detail token issuance or validation internals.
Examples
Uses a protected recipe endpoint, a missing-token 401 response, and Swagger UI's Bearer token authorization dialog.
What it assumes
Assumes an existing ASP.NET Core API and introduces the required JWT package, services, middleware, endpoint policy, and OpenAPI configuration.
What you can do after
Builds JWT protection for a minimal API and tests authenticated requests through Swagger UI.
How it connects
Connects JWT bearer authentication with minimal APIs, authorization policies, authentication schemes, OpenAPI, Swagger UI, OAuth 2.0, and OpenID Connect.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.