Diagnosing JWT 401s after a deployment: WWW-Authenticate details, IDX error codes, issuer/audience/version mismatches, clock skew, JWKS reachability and key rollover, forwarded headers and stripped Authorization headers.
Start with evidence, not guesses. A JwtBearer 401 includes a WWW-Authenticate header with an error_description, and the Microsoft.AspNetCore.Authentication logs at Debug level show an IDX error code.
Authorization header never arrived (stripped by the proxy, or dropped on an HTTP-to-HTTPS redirect).The trade-off: decoding a token at jwt.ms is fast, but only server logs tell you which check failed.
"First I find out which validation step fails instead of guessing. The JwtBearer handler adds an
error_descriptionto theWWW-Authenticateresponse header by default, so a quickcurl -ioften says 'The audience is invalid' or 'The signature key was not found'. I then turn on Debug logging forMicrosoft.AspNetCore.Authenticationin that environment for a short time and read the IDX code. I decode a failing token at jwt.ms, never pasting production tokens into random sites, and compareiss,aud,exp,nbfandkidwith the API's configuration.For example, at [company] we moved an API from [App Service] into [AKS behind an Application Gateway] and everything returned 401. The logs had two problems. First, IDX20803: the pods couldn't fetch the OpenID metadata because egress went through a proxy the handler didn't know about, so no signing keys were loaded. Second, once that was fixed, IDX10214: the new environment's config had the App ID URI as audience, but the API's registration issued v2 tokens whose audience is the client id GUID. [Fixing the egress rule and the audience config took 401s from 100% to zero within the hour.] Other usual suspects: clock skew on a node, which shows as tokens 'not yet valid'; someone hard-coding a signing certificate that stopped working at the IdP's key rollover; the proxy stripping the
Authorizationheader; or a redirect from HTTP to HTTPS, becauseHttpClientdrops theAuthorizationheader when it follows a redirect.The mistake I see is 'fixing' it by turning off
ValidateAudienceorValidateIssuer. The senior line: every 401 has a precise reason in the logs; find it, fix the config, and keep the validation."
| Evidence | Likely cause | Fix |
|---|---|---|
IDX10214 audience invalid |
Wrong Audience, v1/v2 mismatch, token for another API |
Align audience (client id vs App ID URI); request the right scope |
IDX10205 issuer invalid |
Different tenant, v1 vs v2 issuer, self-hosted IdP issuer built from an internal host name | Correct Authority/ValidIssuers; fix the IdP's public origin |
IDX10223 lifetime / IDX10222 not yet valid |
Expired token, client caching tokens, host clock skew | NTP on hosts, refresh logic in clients |
IDX10500 / IDX10503 signature |
Hard-coded key after rollover, wrong environment's IdP | Use Authority metadata, not static keys |
IDX20803 unable to obtain configuration |
Egress blocked, proxy, DNS, TLS inspection | Allow outbound to the IdP, configure the backchannel HttpClient |
| No auth log, request anonymous | Authorization header stripped or dropped on redirect |
Fix proxy config, call the HTTPS URL directly |
| 401 only on large tokens | Header size limits at proxy (e.g. 8 KB) | Raise limits or shrink tokens |
curl -i -H "Authorization: Bearer $TOKEN" https://api/... and read WWW-Authenticate.Microsoft.AspNetCore.Authentication (and Microsoft.IdentityModel events) temporarily.curl the /.well-known/openid-configuration and jwks_uri.Authorization and X-Forwarded-* arrive.date -u) against a reliable source.After adding these checks to our deployment runbook and a start-up probe that fetches the IdP metadata, the next [two] environment migrations had [no] authentication outages, and mean time to diagnose a 401 incident dropped from [~2 hours] to [~10 minutes].
Checks a systematic, evidence-driven approach to authentication failures and knowledge of the real failure modes, without weakening security.
Green flags
WWW-Authenticate details, logs and IDX codesRed flags
ValidateAudience = falseClient -> [Proxy / gateway] -> Kestrel -> UseAuthentication -> JwtBearerHandler
| | |
| |-- strips Authorization? |-- read header (Bearer ...)
| '-- redirects http->https? -------> |-- get config (metadata + JWKS) via backchannel
'-- token for which audience/tenant/version? |-- validate signature (kid -> key)
|-- validate iss, aud, exp/nbf (+ClockSkew)
'-- OnTokenValidated -> principal
JwtBearerOptions.IncludeErrorDetails (default true) puts error and error_description in WWW-Authenticate.JwtBearerEvents.OnAuthenticationFailed gives you the exception; log its type and message, never the token.[PII of type ... is hidden]). In a development environment you can set IdentityModelEventSource.ShowPII = true (and LogCompleteSecurityArtifact in newer versions) to see values; never in production.The handler fetches {Authority}/.well-known/openid-configuration and the JWKS with its Backchannel HttpClient. If the environment needs an outbound proxy, set BackchannelHttpHandler with a proxy, or allow direct egress to the IdP. TLS inspection appliances that re-sign certificates cause certificate errors here. A readiness probe that fetches the metadata catches this at deployment instead of at the first request.
Authorization; IIS ARR and some API gateways need explicit pass-through.HttpClient removes the Authorization header when following a redirect, for security, so a client calling http:// and redirected to https:// arrives anonymous.UseForwardedHeaders matters for OIDC redirect URIs and HTTPS checks, and for self-hosted identity servers that build their issuer from the request host: behind a proxy they can issue tokens with an internal issuer that the API rejects.exp and nbf are absolute UTC seconds. A node a few minutes off causes intermittent failures that follow the node. ClockSkew (5 minutes default) hides small drift; reducing it to 1 minute is fine only if NTP is reliable.
WWW-Authenticate header.IssuerSigningKey from today's JWKS, then simulate rollover by using a token signed with a different key.Authorization and observe an anonymous request with no auth failure logged.Diagnostics you can switch on in an environment: failure reasons logged (never the token), a backchannel proxy, and a readiness check for the IdP metadata.
// Program.cs (.NET 10)
using System.Net;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.Authority = builder.Configuration["Auth:Authority"];
o.Audience = builder.Configuration["Auth:Audience"];
o.IncludeErrorDetails = true; // default; error_description in WWW-Authenticate
// If egress must go through a corporate proxy, the metadata fetch needs it too.
if (builder.Configuration["Egress:Proxy"] is { Length: > 0 } proxy)
o.BackchannelHttpHandler = new HttpClientHandler { Proxy = new WebProxy(proxy), UseProxy = true };
o.Events = new JwtBearerEvents
{
OnMessageReceived = ctx =>
{
// Tells you whether the header even arrived (value redacted).
var hasHeader = ctx.Request.Headers.Authorization.Count > 0;
ctx.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>()
.LogDebug("Authorization header present: {HasHeader}, scheme: {Scheme}", hasHeader, ctx.Request.Scheme);
return Task.CompletedTask;
},
OnAuthenticationFailed = ctx =>
{
ctx.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>()
.LogWarning(ctx.Exception, "JWT validation failed: {ExceptionType}", ctx.Exception.GetType().Name);
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization();
builder.Services.AddHealthChecks().AddCheck<IdpMetadataHealthCheck>("idp-metadata", tags: ["ready"]);
var app = builder.Build();
app.UseForwardedHeaders(); // configured with KnownProxies/KnownNetworks elsewhere
app.UseAuthentication();
app.UseAuthorization();
app.MapHealthChecks("/health/ready", new() { Predicate = r => r.Tags.Contains("ready") });
app.Run();
// Fails readiness if the pod can't reach the identity provider's metadata and keys.
public sealed class IdpMetadataHealthCheck(IConfiguration config) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
{
var manager = new ConfigurationManager<OpenIdConnectConfiguration>(
$"{config["Auth:Authority"]!.TrimEnd('/')}/.well-known/openid-configuration",
new OpenIdConnectConfigurationRetriever());
try
{
var oidc = await manager.GetConfigurationAsync(ct);
return oidc.SigningKeys.Count > 0
? HealthCheckResult.Healthy($"{oidc.SigningKeys.Count} signing keys")
: HealthCheckResult.Unhealthy("No signing keys");
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy("Cannot reach IdP metadata", ex);
}
}
}
# Quick checks from inside the container
curl -si -H "Authorization: Bearer $TOKEN" https://localhost:8443/orders | grep -i www-authenticate
curl -s https://login.microsoftonline.com/$TENANT/v2.0/.well-known/openid-configuration | head -c 300
date -u
ValidateAudience, ValidateIssuer or lifetime checks to get past the 401. Why it is wrong: it turns an outage into a vulnerability that accepts tokens for other APIs or tenants. Instead: find the IDX code and fix the configuration.Authority so keys come from JWKS and refresh automatically.Authorization. Instead: log whether the header arrived (redacted) and test behind the real proxy.ShowPII in production. Why it is wrong: tokens and personal data end up in logs, which may be a notifiable issue. Instead: only in development, briefly.ClockSkew to hours. Why it is wrong: expired tokens stay valid far longer. Instead: fix host time with NTP.401 storms after a deployment are almost always configuration, rarely attacks. The senior moves are to make failures self-explaining (failure reason in logs and metrics, WWW-Authenticate details), to test the real network path in a readiness probe, and to treat validation flags as non-negotiable. I add 'token validation works end to end' as a smoke test in every environment's deployment pipeline.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Debug auth logging temporarily | Active incident | Log volume | Leave it on permanently |
| Failure-reason metric (counter by exception type) | Always | Trivial | Never skip |
| IdP metadata readiness probe | Containers, locked-down egress | One HTTP call per probe interval (cache it) | Hosts with no egress controls (still useful) |
| Post-deploy smoke test with a real token | Every environment | A test client registration | Never skip for public APIs |
Measure: 401 rate by failure reason and by client id; alert when it moves more than a few percent after a release.
CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.Behind a reverse proxy, the app sees the proxy's IP and often plain http. The proxy passes the originals in X-Forwarded-For and X-Forwarded-Proto, but ASP.NET Core only applies them via the ForwardedHeaders middleware, and by default only trusts proxies on loopback. So UseHttpsRedirection sees http, redirects to https, the proxy forwards as http again: a loop.
Fix: UseForwardedHeaders first, configured with the proxy's IPs or network in KnownProxies/known networks. Do not trust all sources, or clients can spoof their IP and scheme.
A JWT is three base64url parts, header.payload.signature. The header says which algorithm and key (alg, kid) signed it; the payload holds claims (iss, aud, sub, exp, scopes); the signature proves nobody changed them. It is signed, not encrypted, so anyone holding it can read it: no personal or secret data.
AddJwtBearer with Authority and Audience validates issuer, audience, lifetime and signature (with a 5-minute ClockSkew).The trade-off: validation is local and fast, but a stolen token is valid until exp, so keep access tokens short-lived.
How to tell it (STAR)
**S:** When we moved our [orders] API to [AKS], every request started failing with 401, affecting [~20] services. **T:** I led the diagnosis. **A:** I rolled traffic back, then used the `WWW-Authenticate` details and Debug authentication logs instead of guessing: the pods couldn't reach the identity provider's metadata through the firewall, and once that was open, the audience config didn't match our v2 tokens. I fixed both, then added a metadata readiness probe and a real-token smoke test to the pipeline. **R:** The second cut-over had [zero] authentication errors, and later migrations caught similar issues at deploy time instead of in production.
Last updated 23 Nov 2026.