An ASP.NET Core API answers 401 for a JWT that decodes and looks valid; how do you find the cause using IncludeErrorDetails, logging and JwtBearerEvents?
answer
- read the WWW-Authenticate header first
- IncludeErrorDetails defaults to true
- 'Failed to validate the token.' is Information
- OnAuthenticationFailed exposes the exception
- SecurityToken is a JsonWebToken since 8
basics
~10 sRead the 401's WWW-Authenticate header: IncludeErrorDetails, on by default, adds error="invalid_token" and a reason. Then let Microsoft.AspNetCore.Authentication log at Information, or read context.Exception in JwtBearerEvents.OnAuthenticationFailed.
solid answer
~40 sStart with the response. With `IncludeErrorDetails` (default `true`) a failed token yields `WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'x' is invalid"` or similar; a bare `Bearer` means no token reached the handler — missing header, missing `Bearer ` prefix, or a default scheme other than `Bearer`. Next, logs: the handler writes "Failed to validate the token." with the exception at **Information**, which the template's `"Microsoft.AspNetCore": "Warning"` hides, so lower `Microsoft.AspNetCore.Authentication` in Development. For code-level detail, `JwtBearerEvents.OnAuthenticationFailed` exposes `context.Exception` (`SecurityTokenExpiredException`, `SecurityTokenInvalidAudienceException`, `SecurityTokenSignatureKeyNotFoundException`), and `OnChallenge` shows `AuthenticateFailure`; call `HandleResponse()` there if you write the body yourself. In ASP.NET Core 8+, `OnTokenValidated` gets a `JsonWebToken`, not a `JwtSecurityToken`.
code
csharp · 23 linesbuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://id.example.com/";
options.Audience = "mobile-banking-api";
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
var log = context.HttpContext.RequestServices
.GetRequiredService<ILogger<Program>>();
log.LogWarning(context.Exception, "Bearer token rejected");
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
var token = (JsonWebToken)context.SecurityToken;
if (!token.TryGetPayloadValue<string>("device_id", out _))
context.Fail("Token has no device binding.");
return Task.CompletedTask;
}
};
});go deeper
Know to read the WWW-Authenticate header on a 401 and that error_description names the failed check.
Map each error_description to its cause and know which JwtBearerEvents event exposes the exception and which writes the challenge.
Run the triage in order: 401 versus 403, description, header and default scheme, Information-level logs, then iss, aud, exp and kid against configuration; know the .NET 8 JsonWebToken change.
Decide what failure detail callers see versus logs, and make token-rejection reasons observable across services without leaking validation settings.
## Read the response before the code When the mobile banking API rejects a token that looks fine in a decoder, the first evidence is already in the 401. `JwtBearerHandler.HandleChallengeAsync` builds the `WWW-Authenticate` header, and **`IncludeErrorDetails` defaults to `true`**, so when authentication failed it adds `error="invalid_token"` and an `error_description` built from the validation exceptions: - `The audience '...' is invalid` — the token was minted for another API. - `The issuer '...' is invalid` — a different tenant, a v1 versus v2 endpoint, or a typo in `ValidIssuer`. - `The token expired at '...'` — expired beyond `ClockSkew`. - `The token is not valid before '...'` — the provider's clock is ahead. - `The signature key was not found` — signed with a key this API's metadata does not list, often a token from another environment. - `The signature is invalid` — the token was altered, or the wrong key is configured. A challenge with a **bare `WWW-Authenticate: Bearer`** and no error means the handler never saw a failing token: the header was missing, lacked the `Bearer ` prefix, or the default authenticate scheme is not the JWT one (a cookie default in a mixed app), so the JWT handler never ran. Some teams set `IncludeErrorDetails = false` outside development because the description reveals the expected audience and issuer. ## Then the logs `JwtBearerHandler` logs "Failed to validate the token." with the full exception, including the IdentityModel `IDX` code, at **Information** level, and its authentication handler base class logs "Bearer was not authenticated. Failure message: ..." at Information too. The `webapi` template's `appsettings.json` sets `"Microsoft.AspNetCore": "Warning"`, so both lines are filtered out by default. In Development, add `"Microsoft.AspNetCore.Authentication": "Information"` (or `Debug`) to see them. ## Then the events `JwtBearerEvents` exposes the handler's stages as delegates: | Event | Runs when | Useful for | |---|---|---| | `OnMessageReceived` | before the header is read | taking the token from another place; `context.Token` | | `OnTokenValidated` | after validation succeeds | extra checks; `context.Fail(...)` rejects | | `OnAuthenticationFailed` | validation threw or failed | logging `context.Exception` | | `OnChallenge` | a 401 is about to be written | reading `AuthenticateFailure`, custom bodies | | `OnForbidden` | an authenticated user is forbidden | customising the 403 | Three behaviours matter when you use them: 1. **`OnChallenge` and the body.** If you write a response body yourself, call `context.HandleResponse()`. Otherwise the handler goes on to set the status and its `WWW-Authenticate` header, which fails once your body has started the response. 2. **Exceptions inside events.** An exception thrown by an event handler such as `OnMessageReceived` or `OnTokenValidated` is logged as "Exception occurred while processing message." at Error, passed to `OnAuthenticationFailed`, and rethrown unless that event sets a result. A bug in `OnTokenValidated` therefore typically surfaces as a server error, not a 401. Token validation failures themselves are caught separately and become ordinary 401s. 3. **The token type changed in ASP.NET Core 8.** Validation now runs through `TokenHandlers` (a `JsonWebTokenHandler`), so `TokenValidatedContext.SecurityToken` is a `JsonWebToken`. Code that casts it to `JwtSecurityToken` gets `null`. Cast to `JsonWebToken`, or set `UseSecurityTokenValidators = true` to use the obsolete `SecurityTokenValidators` path. ## A short triage order 1. Is it 401 or 403? A 403 means authentication succeeded and a policy refused; look at authorization, not the token. 2. Read `error_description`. 3. If there is none, check the header format and which scheme authenticates by default. 4. Turn up `Microsoft.AspNetCore.Authentication` logging and read the `IDX` message. 5. Compare the token's `iss`, `aud`, `exp` and `kid` with what the API expects: `Authority`, `Audience`, server time and the provider's published keys. A frequent root cause in this scenario is the client sending the **ID token** instead of the **access token**; its audience is the client app, so the API reports an invalid audience.
- The 401 carries only WWW-Authenticate: Bearer with no error. What does that tell you?The JWT handler produced no failure: either it found no token (no header, or no `Bearer ` prefix) and returned NoResult, or it never ran because another scheme is the default authenticate scheme. Check the client's header and the scheme the endpoint's policy uses before looking at the token's contents.
- Should OnChallenge write a ProblemDetails body for every 401?It can, but it must call `context.HandleResponse()` after writing, or the handler goes on to set the status and header itself after the body has started. Keep the details generic in production; `AuthenticateFailure` is for logs, not for callers.
- A bare WWW-Authenticate: Bearer means the token's signature was invalid.
- Token validation failures are logged at Warning, so the template configuration shows them.
- Writing a body in OnChallenge is enough; HandleResponse is optional.
- Cast context.SecurityToken to JwtSecurityToken in OnTokenValidated on ASP.NET Core 10.
- An exception thrown in OnTokenValidated just turns into a 401.
Assumes ASP.NET Core 10; since ASP.NET Core 8 JwtBearer validates through TokenHandlers, so event contexts carry a JsonWebToken and SecurityTokenValidators is obsolete.