📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

After deploying your ASP.NET Core API behind a reverse proxy in a new environment, every request returns 401 even though clients send what look like valid tokens. How do you diagnose it, and what are the usual causes: issuer or audience mismatch, clock skew, signing-key rollover, the HTTPS scheme, or headers lost on the way?

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.

Senior Debugging Advanced aspnet-core authentication debugging jwt reverse-proxy security

🎯 Key points

  • Read the WWW-Authenticate error_description and the IDX code in Debug authentication logs
  • IDX10214 audience, IDX10205 issuer, IDX10223 expired, IDX10503/IDX10517 signature, IDX10500 no key; malformed or truncated tokens also fail
  • IDX20803: can't fetch OIDC metadata or JWKS (egress firewall, proxy, DNS)
  • v1 vs v2 tokens change iss and aud
  • Clock skew on hosts or containers; ClockSkew default 5 minutes
  • Hard-coded signing keys break at key rollover and can't be rotated quickly after a compromise; use Authority metadata
  • Proxy strips Authorization or HttpClient drops it on redirects; forwarded headers for scheme and host
  • Fix the config, never disable validation; add a metadata readiness probe and a real-token smoke test after each deployment

⏱ 30-second answer

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.

  • IDX10214 / IDX10205: audience or issuer mismatch, often a different tenant, App ID URI or v1 vs v2 token.
  • IDX10223: expired, or clock skew on the host.
  • IDX10500/10503: signing key not found or signature invalid, a hard-coded key after rollover.
  • IDX20803: the API can't reach the metadata/JWKS endpoint through the egress firewall or proxy.
  • No error at all: the 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.

🗣 Full answer (senior)

How I would answer this in an interview

"First I find out which validation step fails instead of guessing. The JwtBearer handler adds an error_description to the WWW-Authenticate response header by default, so a quick curl -i often says 'The audience is invalid' or 'The signature key was not found'. I then turn on Debug logging for Microsoft.AspNetCore.Authentication in 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 compare iss, aud, exp, nbf and kid with 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 Authorization header; or a redirect from HTTP to HTTPS, because HttpClient drops the Authorization header when it follows a redirect.

The mistake I see is 'fixing' it by turning off ValidateAudience or ValidateIssuer. The senior line: every 401 has a precise reason in the logs; find it, fix the config, and keep the validation."


Symptom to cause

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

Diagnostic steps

  1. curl -i -H "Authorization: Bearer $TOKEN" https://api/... and read WWW-Authenticate.
  2. Enable Debug logs for Microsoft.AspNetCore.Authentication (and Microsoft.IdentityModel events) temporarily.
  3. Decode the token in a trusted tool (jwt.ms, or locally) and compare claims to config.
  4. From inside the pod or app, curl the /.well-known/openid-configuration and jwks_uri.
  5. Log the request headers the app actually receives (redact the token value) to see if Authorization and X-Forwarded-* arrive.
  6. Check host time (date -u) against a reliable source.

Production example

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].

🔍 What the interviewer is checking

Checks a systematic, evidence-driven approach to authentication failures and knowledge of the real failure modes, without weakening security.

Green flags

  • Starts with WWW-Authenticate details, logs and IDX codes
  • Knows v1/v2, issuer and audience pitfalls
  • Considers metadata reachability, key rollover and clock skew
  • Checks whether the header actually reached the app
  • Refuses to disable validation

Red flags

  • First instinct is ValidateAudience = false
  • Pastes production tokens into random websites
  • Doesn't consider the proxy or network path

📚 Learn in depth

1. Where validation can fail

Client -> [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

2. Making the handler talk

  • 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.
  • Identity model messages hide personal data ([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.

3. Configuration retrieval

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.

4. Proxies and headers

  • Some proxies and WAF rules drop or rename 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.

5. Time

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.

Try it yourself

  1. Call a protected endpoint with a token for another audience and read the WWW-Authenticate header.
  2. Block outbound traffic to the IdP (hosts file or network policy) and restart the API: find IDX20803 in the logs.
  3. Hard-code an IssuerSigningKey from today's JWKS, then simulate rollover by using a token signed with a different key.
  4. Put YARP in front of the API with a transform that removes Authorization and observe an anonymous request with no auth failure logged.
  5. Write a readiness check that downloads the OIDC metadata and fails if it can't.

💻 Code

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

⚠ Common mistakes

  • Mistake: Disabling 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.
  • Mistake: Hard-coding the signing key or certificate. Why it is wrong: the IdP rotates keys and the API fails at the next rollover. Instead: use Authority so keys come from JWKS and refresh automatically.
  • Mistake: Assuming the token reached the app. Why it is wrong: proxies, WAF rules and redirects can strip Authorization. Instead: log whether the header arrived (redacted) and test behind the real proxy.
  • Mistake: Pasting production tokens into public websites. Why it is wrong: tokens are live credentials and may contain personal data. Instead: use jwt.ms (client-side) or decode locally, and prefer expired or test tokens.
  • Mistake: Turning on 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.
  • Mistake: Ignoring egress requirements for the metadata endpoint. Why it is wrong: the API can't load signing keys and every token fails. Instead: allow outbound access or configure the backchannel proxy, and add a readiness check.
  • Mistake: Increasing ClockSkew to hours. Why it is wrong: expired tokens stay valid far longer. Instead: fix host time with NTP.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions forwarded headers or the proxy Why: Checks they can configure forwarded headers safely
    How to answer
    • A forward proxy sits in front of clients (corporate egress proxy): clients send requests through it to the internet. For HTTPS it tunnels with CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.
    • A reverse proxy sits in front of servers (nginx, Envoy, YARP, App Gateway, ingress): it terminates TLS, routes, load balances, caches and adds headers.

    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.

  2. When: Candidate mentions issuer, audience or signature validation Why: Checks deeper understanding of JWT validation parameters
    How to answer

    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.

    • RS256/ES256: the identity provider signs with a private key and APIs verify with the public key from its JWKS endpoint. HS256 uses one shared secret, so every verifier could also forge tokens.
    • In ASP.NET Core, 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.

🛠 Real-world problems: how you handle them

All requests 401 after moving the API to AKS behind Application Gateway
Situation
An [orders] API moved from App Service to [AKS] behind [Azure Application Gateway] in Australia East. Egress from the cluster went through [a firewall with an allow-list]. [~20] client services called it.
Signals
100% 401 responses immediately after cut-over; client teams reported 'token rejected'; no application errors other than authentication warnings; Application Insights showed the 401 rate jump from [<0.5%] to [100%].
Investigation
Read `WWW-Authenticate` on a failing call; enabled Debug logs for `Microsoft.AspNetCore.Authentication` and found IDX20803 (can't obtain configuration); `curl` from a pod to the metadata URL timed out; after opening egress, logs showed IDX10214 and jwt.ms showed `aud` as the client id GUID while config expected the App ID URI; compared with the App Service configuration and found the old environment set both audiences.
Resolution
Rolled traffic back to App Service within [15 minutes]. Added the identity provider endpoints to the firewall allow-list, set `Audience` to accept both the client id and App ID URI as the old environment did, and redeployed; 401s returned to baseline.
Prevention
A readiness probe that fetches IdP metadata; a post-deployment smoke test that calls the API with a real token from a test client; a failure-reason metric with an alert; an environment checklist covering egress, audience and token version.

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.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me