Bearer authentication gives a client access to a protected resource using a token: a string containing authentication details about a user or application. Anyone holding the token can use it without proving they originally received it or possessing an additional key. section 25.1.2 section 25.2
Treat a bearer token like a password. Avoid putting it in a URL query string, where it might be logged. Tokens are typically signed to detect tampering, but signing does not necessarily make their contents secret. section 25.2 section 25.1.2
An identity provider can handle sign-in and return tokens to a browser or mobile client. The client then sends a token to an API, allowing the API to identify the logged-in user without managing the sign-in itself. This arrangement can also support single sign-on across services. section 25.1.2
Figure 25.4 An alternative architecture involves using a central identity provider to handle all the authentication and user management for the system. Tokens are passed back and forth among the identity provider, apps, and APIs.
Follow how a central identity provider, clients, and APIs exchange tokens. section 25.1.2
JSON Web Tokens (JWTs) are a common bearer-token format. A JWT has a header, payload, and signature. Always verify the signature when receiving one. A JWT is not encrypted by default, so its contents can be read; JWE can wrap and encrypt it. section 25.7
In ASP.NET Core, authentication middleware validates and deserializes a bearer token. For a valid token, it creates a ClaimsPrincipal and sets HttpContext.User. Authorization is a separate step: an endpoint can require authorization to restrict who may call it. section 25.7 section 25.2
Figure 25.8 When an API request contains a bearer token, the token is validated and deserialized by the authentication middleware. The middleware creates a ClaimsPrincipal from the token, optionally transforming it with additional claims, and sets the HttpContext.User property. Subsequent middleware sees the request as authenticated.
See how a token becomes the authenticated user for a request. section 25.2
Test a minimal API locally
Add the Microsoft.AspNetCore.Authentication.JwtBearer package and register authentication with AddAuthentication().AddJwtBearer(). Run dotnet user-jwts create to configure support for a local test token and print it. Send it in the request header as Authorization: Bearer <token>. Protect an endpoint with RequireAuthorization() or [Authorize]. section 25.7
For Swagger UI, describe the security scheme and its use in the OpenAPI document. With Swashbuckle, use AddSecurityDefinition() to define the scheme and AddSecurityRequirement() to apply it. In the Authorize dialog, enter Bearer <token>; Swagger UI then adds the Authorization header to requests. section 25.5
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
Inspect the Swashbuckle configuration for a JWT bearer security scheme. section 25.5




