skip to content

In ASP.NET Core, how do you make a Web API accept an identity provider's access tokens with AddJwtBearer, and what does the handler do?

level: juniorimportance: must knowfreq 78%

answer

  1. a NuGet package, not the shared framework
  2. JwtBearerDefaults.AuthenticationScheme is "Bearer"
  3. Authority leads to the discovery document
  4. Audience must match the token's aud
  5. no header: NoResult, not 401

basics

~10 s

Reference Microsoft.AspNetCore.Authentication.JwtBearer, call AddAuthentication().AddJwtBearer() with Authority and Audience, and mark endpoints with [Authorize] or RequireAuthorization. The handler reads the Bearer header, validates the token and puts its claims in HttpContext.User.

solid answer

~40 s

The JWT handler ships as the `Microsoft.AspNetCore.Authentication.JwtBearer` package. You register it with `AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o => { o.Authority = ...; o.Audience = ...; })`. `Authority` tells the handler where the identity provider's `/.well-known/openid-configuration` document lives, and from it the handler learns the issuer and the signing keys; `Audience` becomes the expected `aud` value. On each request the handler takes the token after `Bearer ` in the `Authorization` header and validates signature, issuer, audience and lifetime; success turns the claims into `HttpContext.User`. A request with no token is not rejected by the handler: it returns `NoResult`, and only an endpoint that requires authorization turns that into a 401 challenge with `WWW-Authenticate: Bearer`. There is no redirect and no cookie.

code

http · 6 lines
http
GET /accounts/me HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjEyMyJ9.eyJzdWIiOiJjLTQ0MSIsImF1ZCI6InBheW1lbnRzLWFwaSJ9.c2lnbmF0dXJl

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'payments-api' is invalid"

go deeper

for a junior

Recall the package name, the AddJwtBearer call with Authority and Audience, and that [Authorize] or RequireAuthorization is what makes a missing token a 401.

for a middle

Explain the per-request steps: header read, TokenHandlers validation of signature, issuer, audience and lifetime, the principal in HttpContext.User, and NoResult when no token is present.

for a senior

Show you know what Authority really triggers — discovery, cached keys, refresh on an unknown key — and why the audience check is what keeps a token for one API out of another.

for a principal

Discuss where validation belongs across many services: each API validating against the provider's keys versus a gateway, and what each choice means for audience design.

## What the JWT bearer handler is A **JSON Web Token (JWT)** access token is a signed string an identity provider issues to a client app; the client sends it on every API call in the `Authorization: Bearer <token>` header. In ASP.NET Core the component that checks those tokens is an **authentication handler**, `JwtBearerHandler`, registered under a **scheme** name. The constant `JwtBearerDefaults.AuthenticationScheme` holds that name: `"Bearer"`. Unlike the cookie handler, the JWT handler is **not part of the shared framework**. A project adds the `Microsoft.AspNetCore.Authentication.JwtBearer` NuGet package, which brings `AddJwtBearer` and pulls in the Microsoft.IdentityModel libraries that do the actual token validation. ## Wiring it up for a mobile banking API The banking app signs customers in at an external identity provider and calls the API with the access token it received. The API only has to validate: ```csharp using System.Security.Claims; using Microsoft.AspNetCore.Authentication.JwtBearer; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "https://id.example.com/"; options.Audience = "mobile-banking-api"; }); builder.Services.AddAuthorization(); var app = builder.Build(); app.MapGet("/accounts/me", (ClaimsPrincipal user) => Results.Ok(new { customerId = user.FindFirstValue(ClaimTypes.NameIdentifier) })) .RequireAuthorization(); app.Run(); ``` Two settings carry most of the weight: - **`Authority`** — the base address of the identity provider. When `MetadataAddress` is empty, the handler appends `.well-known/openid-configuration` to it, downloads that **discovery document** over HTTPS and reads the issuer name and the location of the provider's public signing keys. A `ConfigurationManager` caches the result. - **`Audience`** — the identifier of *this* API. A post-configure step copies it into `TokenValidationParameters.ValidAudience` when that is empty, so a token minted for some other API is refused. ## What happens on each request 1. The authentication middleware asks the default scheme, here `Bearer`, to authenticate. 2. `JwtBearerEvents.OnMessageReceived` runs first and may supply the token from elsewhere. 3. Otherwise the handler reads the `Authorization` header. **No header, or no `Bearer ` prefix, means `AuthenticateResult.NoResult()`** — the request simply stays anonymous. 4. With a token, each entry in `TokenHandlers` (by default one `JsonWebTokenHandler`) validates it against `TokenValidationParameters`: signature against the provider's keys, issuer, audience and lifetime. 5. On success the handler builds a `ClaimsPrincipal`, raises `OnTokenValidated`, stores the raw token in the authentication properties (`SaveToken` defaults to `true`) and returns success; the middleware sets `HttpContext.User`. 6. On failure it raises `OnAuthenticationFailed` and returns `AuthenticateResult.Fail`. Authentication never rejects a request by itself. The decision comes from **authorization**: an endpoint with `[Authorize]` or `RequireAuthorization()` and an unauthenticated user triggers a **challenge**, which the JWT handler answers with status 401 and a `WWW-Authenticate: Bearer` header (with `error="invalid_token"` and a description when a token was present but failed). | Request | Endpoint without authorization | Endpoint requiring authorization | |---|---|---| | no token | runs anonymously | 401, `WWW-Authenticate: Bearer` | | valid token | runs, `User` filled | runs, `User` filled | | expired or wrong-audience token | runs anonymously | 401 with `error="invalid_token"` | ## How it differs from cookie authentication - No sign-in call: the API never calls `SignInAsync`; the identity provider issued the token. - No redirect: a challenge is always a 401, never a trip to a login page. - No server state: every request carries its own proof, so any instance can validate it once it has the provider's keys. Where `UseAuthentication` sits in the pipeline and how `[Authorize]` policies decide are separate topics; this answer is about what the handler does once it runs.

  • Does the JWT handler call the identity provider on every request?
    No. It downloads the discovery document and the signing keys once through its `ConfigurationManager` and caches them, refreshing on an interval or when a token arrives signed with a key it does not know (`RefreshOnIssuerKeyNotFound` defaults to `true`). Each request is then validated locally from the cached keys, with no call to the provider.
  • Why does the API need Audience when the token's signature is already valid?
    A valid signature only proves which provider issued the token. The same provider issues tokens for many APIs, so without an audience check a token the customer obtained for, say, a loyalty API would also open the banking API. `Audience` becomes `ValidAudience`, and the handler refuses any token whose `aud` does not match.
  • Where is the raw token available after authentication?
    Because `SaveToken` defaults to `true`, the handler stores it as `access_token` in the authentication properties, so `await HttpContext.GetTokenAsync("access_token")` returns it, for example to forward it to a downstream API.

  • The JWT handler returns 401 itself whenever a request has no Authorization header.
  • AddJwtBearer is in the shared framework, so no package reference is needed.
  • Authority is the URL the API redirects unauthenticated users to.
  • The handler calls the identity provider to validate every token.
  • A valid signature is enough; the audience check is optional hardening.