Securing APIs with JWT bearer tokens
APIs used by mobile apps and single-page apps usually authenticate with bearer tokens instead of cookies. This lesson explains what a JWT contains, how to validate tokens from an identity provider in ASP.NET Core, and how to protect endpoints with policies and scopes.
- StartClient signs inIdentity provider issues a JWT
- Step 2Request to APIAuthorization: Bearer <token>
- Step 3JwtBearer middlewareChecks signature, issuer, audience, expiry
- Step 4AuthorizationPolicy checks the scope or role
- EndAction runsUser claims available in User
What a JWT is
A JSON Web Token has three base64url parts: a header, a payload of claims (who the user is, which app it is for, when it expires) and a signature. The API checks the signature with the issuer's public key, so it can trust the claims without calling a database.
Tokens are signed, not encrypted: anyone can read the payload, so never put secrets in it. The client sends it in the Authorization: Bearer <token> header.
Validating tokens
Let an identity provider issue tokens (Microsoft Entra ID, Auth0, Keycloak, Duende IdentityServer and so on). The API only validates them. The middleware downloads the signing keys from the provider's metadata automatically.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.Authority = "https://login.microsoftonline.com/<tenant-id>/v2.0";
o.Audience = "api://shop-api";
o.TokenValidationParameters.ValidateLifetime = true; // default; shown for clarity
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("orders.write", p => p.RequireAuthenticatedUser().RequireClaim("scp", "orders.write"));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();Protecting endpoints
[ApiController, Route("api/orders"), Authorize]
public class OrdersApiController(ShopContext db) : ControllerBase
{
[HttpGet]
public async Task<IEnumerable<OrderDto>> Mine()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier)!;
return await db.Orders.Where(o => o.UserId == userId)
.Select(o => new OrderDto(o.Id, o.Total)).ToListAsync();
}
[HttpPost, Authorize(Policy = "orders.write")]
public IActionResult Create(CreateOrder input) => Ok();
}Mistakes to avoid
- Issuing your own tokens with a hard-coded signing key in appsettings.json; use an identity provider or keep keys in Key Vault.
- Turning off ValidateIssuer, ValidateAudience or ValidateLifetime to make an error go away.
- Long-lived access tokens; keep them short (minutes to an hour) and use refresh tokens in the client.
- Storing tokens in localStorage in browser apps exposes them to XSS; a backend-for-frontend with cookies is safer for SPAs.
- Always serve APIs over HTTPS.
Interview question
How does an ASP.NET Core API validate a JWT without calling the identity provider on every request?
At startup the JWT bearer middleware downloads the provider's OpenID Connect metadata and public signing keys from the Authority URL and caches them. For each request it checks the token's signature with those keys, then the issuer, audience and expiry. If all pass, it builds the user's ClaimsPrincipal from the token's claims, with no extra network call.
Want the full details? Read the official Microsoft documentation for this topic.