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

📚 Interview question

What is a JWT? Explain its structure, how it is signed (RS256 vs HS256), which TokenValidationParameters actually matter when an ASP.NET Core API validates one, why you shouldn't put sensitive data in it, and why revoking a JWT is hard.

JSON Web Tokens: header, payload and signature, symmetric vs asymmetric signing, validation in ASP.NET Core JwtBearer, data exposure and the revocation problem.

Intermediate Theory Intermediate aspnet-core authentication jwt oauth2 security token-validation

🎯 Key points

  • Three base64url parts: header (alg, kid), payload (claims), signature
  • Signed, not encrypted: anyone can read the payload
  • RS256/ES256 asymmetric (IdP signs, APIs verify via JWKS) vs HS256 shared secret
  • Validate issuer, audience, lifetime and signature; ClockSkew default 5 minutes
  • Pin ValidAlgorithms and RequireSignedTokens to block alg none and RS256/HS256 confusion
  • MapInboundClaims changes claim names, which drives User.Identity.Name and IsInRole
  • Revocation: 5-15 min access tokens + rotating refresh tokens; jti deny-list or introspection for high-risk APIs

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"A JWT, RFC 7519, is a compact token with three base64url-encoded parts separated by dots. The header carries alg, for example RS256, and kid, which key signed it. The payload carries claims: registered ones like iss, aud, sub, exp, nbf, iat, jti, plus whatever the issuer adds, like scp or roles. The signature covers the first two parts. Because it's only signed, the payload is readable by anyone who has the token, so I never put personal data, secrets or internal details in it.

For signing, I want asymmetric keys: RS256 or ES256. The identity provider, say Microsoft Entra ID, holds the private key and publishes public keys at its JWKS endpoint, so each API can verify but none can mint tokens. HS256 uses one shared secret, so every service that verifies could also forge, and the secret has to be distributed and rotated. In ASP.NET Core I configure AddJwtBearer with Authority and Audience; the handler downloads the OpenID Connect metadata, caches the signing keys, refreshes them when it sees an unknown kid, and validates issuer, audience, lifetime and signature. ClockSkew defaults to five minutes, which I usually reduce.

The mistake I see is turning validation off to 'make it work': ValidateAudience = false, or accepting any issuer in a multi-tenant setup, so a token for a different API is accepted. And people forget revocation: the API never calls the issuer, so a stolen token works until exp. The senior answer is short access tokens, five to fifteen minutes, refresh tokens with rotation for the session, and a deny-list only where the risk justifies it."


Anatomy

eyJhbGciOiJSUzI1NiIsImtpZCI6IjEyMyJ9 . eyJpc3MiOiJodHRwczovL2xvZ2luLi4uIiwiYXVkIjoiYXBpOi8vb3JkZXJzIiwiZXhwIjoxNzAwMDAwMDAwfQ . <signature>
        header {alg, kid, typ}                        payload {iss, aud, sub, exp, scp ...}

Signing algorithms

Algorithm Key Who can verify Who can forge Use it when
HS256 Shared secret (>= 256 bits) Anyone with the secret Anyone with the secret Single service issuing and validating its own tokens
RS256 RSA 2048+ key pair Anyone with the public key Only the private key holder Standard for IdP-issued tokens
ES256 ECDSA P-256 key pair Public key holders Private key holder Smaller signatures, same model as RS256

Validation parameters that matter

Parameter Why
ValidIssuer(s) / ValidateIssuer Rejects tokens from another tenant or IdP
ValidAudience(s) / ValidateAudience Rejects tokens issued for a different API
ValidateLifetime, ClockSkew Enforces exp/nbf; 5 minutes default skew
IssuerSigningKeys, ValidateIssuerSigningKey Signature must verify with a trusted key
ValidAlgorithms Pins RS256/ES256 and blocks algorithm confusion
RequireSignedTokens, RequireExpirationTime On by default; never turn off

Production example

In [company]'s order API we found ValidateAudience = false, which meant any token from our Entra tenant, including one for an internal HR app, was accepted. Restoring audience validation and pinning ValidAlgorithms rejected [~3%] of traffic from two misconfigured clients, which we fixed by requesting the right scope before turning enforcement on.

🔍 What the interviewer is checking

Checks that the candidate understands JWTs as signed (not encrypted) bearer tokens and validates them properly, rather than treating them as magic session objects.

Green flags

  • Explains signed vs encrypted and keeps sensitive data out
  • Prefers asymmetric signing and knows how keys are discovered (JWKS, kid)
  • Names issuer, audience, lifetime and signature validation, plus clock skew
  • Explains the revocation trade-off and short lifetimes

Red flags

  • Says the JWT payload is encrypted
  • Suggests turning off validation flags
  • Proposes multi-day access tokens in localStorage

📚 Learn in depth

1. Encoding and signing

The signing input is base64url(header) + "." + base64url(payload). For RS256 the issuer computes RSASSA-PKCS1-v1_5 over SHA-256 of that input with its private key; the verifier recomputes the hash and checks it with the public key. Any byte change in header or payload breaks the signature. JWE (encrypted JWTs) exist but are rare for access tokens; if the data is sensitive, keep it out of the token instead.

2. How JwtBearer finds keys

Authority = https://login.microsoftonline.com/{tenant}/v2.0
   -> GET {Authority}/.well-known/openid-configuration  (issuer, jwks_uri)
   -> GET jwks_uri  (public keys with kid)
   -> cached by ConfigurationManager (AutomaticRefreshInterval 12 h;
      refresh sooner on unknown kid, rate limited by RefreshInterval)

This is why key rollover is usually invisible, and why a firewall blocking outbound calls to the IdP breaks validation at start-up or at the next rollover. Since .NET 8 the handler uses JsonWebTokenHandler from Microsoft.IdentityModel.JsonWebTokens by default, which is faster and async; the old JwtSecurityTokenHandler is only used if you opt back in.

3. Claims mapping

By default the handler maps short JWT claim names to long WS-Federation URIs (sub becomes ClaimTypes.NameIdentifier). Setting MapInboundClaims = false keeps the original names, which is clearer but changes what User.Identity.Name and IsInRole read unless you set NameClaimType and RoleClaimType.

4. Known attacks

  • alg: none: unsigned token accepted by a naive library. Modern handlers reject it when RequireSignedTokens is on.
  • Algorithm confusion: an RS256 public key used as an HS256 secret. Prevented by typed keys and ValidAlgorithms.
  • Token substitution: a valid token for API A sent to API B. Prevented by audience validation.
  • Leakage: tokens in URLs, logs or localStorage. Prevented by headers only, log scrubbing and the BFF pattern.

5. Revocation options

short exp (5-15 min) + refresh token rotation   <- default
jti deny-list in Redis, checked in OnTokenValidated   <- high-risk APIs
reference tokens + introspection (RFC 7662)        <- immediate, but a call per request

Try it yourself

  1. Paste a dev token into jwt.ms and identify iss, aud, exp and kid.
  2. Change one character in the payload and confirm the API returns 401 with IDX10511/signature errors in Debug logs.
  3. Create a token for another audience and confirm it is rejected; then set ValidateAudience = false and see it accepted.
  4. Set ClockSkew = TimeSpan.Zero and test a token that has just expired.
  5. Benchmark JsonWebTokenHandler.ValidateTokenAsync with BenchmarkDotNet to see how cheap local validation is.

💻 Code

Strict JWT bearer validation for an API whose tokens come from an OpenID Connect provider.

// Program.cs (.NET 10)
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Auth:Authority"]; // metadata + JWKS
        options.Audience = builder.Configuration["Auth:Audience"];   // e.g. api://orders
        options.MapInboundClaims = false;                           // keep 'sub', 'roles' as issued

        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidAlgorithms = [SecurityAlgorithms.RsaSha256],      // pin the algorithm
            ClockSkew = TimeSpan.FromMinutes(1),                    // default is 5
            NameClaimType = "name",
            RoleClaimType = "roles"
        };

        options.Events = new JwtBearerEvents
        {
            // Log the reason, never the token itself.
            OnAuthenticationFailed = ctx =>
            {
                ctx.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>()
                    .LogWarning("JWT rejected: {Reason}", ctx.Exception.GetType().Name);
                return Task.CompletedTask;
            }
        };
    });

builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/orders", () => Results.Ok()).RequireAuthorization();
app.Run();

⚠ Common mistakes

  • Mistake: Disabling ValidateAudience or ValidateIssuer to fix a 401. Why it is wrong: tokens meant for other APIs or tenants become valid here. Instead: find the real mismatch (scope, tenant, v1 vs v2 endpoint) and fix the client or config.
  • Mistake: Putting email, date of birth or internal flags in the payload. Why it is wrong: the payload is only base64url, readable by the browser, proxies and anyone who logs it. Instead: carry identifiers and scopes; look up personal data server-side.
  • Mistake: Using HS256 with a short or shared secret across many services. Why it is wrong: any service can forge tokens and a weak secret can be brute-forced offline. Instead: asymmetric signing from an IdP, or at least a 256-bit random secret in Key Vault.
  • Mistake: Trusting the token's alg header without pinning algorithms. Why it is wrong: it opens algorithm confusion (an RS256 public key used as an HS256 secret) and alg: none in weaker libraries. Instead: set ValidAlgorithms, keep RequireSignedTokens on and use typed keys from the IdP's JWKS.
  • Mistake: Long-lived access tokens (hours or days). Why it is wrong: a token leaked through a log, proxy or browser extension keeps working with full privileges until exp, there is no way to recall it, and role changes or account disablement don't take effect. Instead: 5–15 minute access tokens plus refresh token rotation (each refresh returns a new refresh token and reuse of an old one revokes the family) or a BFF session cookie.
  • Mistake: Storing tokens in localStorage. Why it is wrong: any XSS can read and exfiltrate them. Instead: a BFF with HttpOnly cookies, or memory-only storage for short tokens.
  • Mistake: Changing MapInboundClaims without setting NameClaimType and RoleClaimType. Why it is wrong: User.Identity.Name becomes null and [Authorize(Roles = ...)] silently stops matching. Instead: decide the claim names once and configure both properties.
  • Mistake: Decoding the token manually with ReadJwtToken and trusting the claims. Why it is wrong: reading is not validating; the signature is never checked. Instead: let the JwtBearer handler validate and read claims from HttpContext.User.

🏛 Senior insight: trade-offs

JWTs trade revocability for scalability: validation is a local CPU operation (microseconds), so the API needs no call to the issuer, but the issuer also cannot take a token back. That is a good trade for access tokens that live minutes and a bad one for long sessions. Where revocation must be immediate (a payments API moving money, an admin API that can export customer data, a health record system), I add a per-request check: a jti or 'issued before' deny-list in Redis costs well under a millisecond and closes the window. When I review JWT code, the first things I look for are disabled validation flags, the token lifetime and where the token is stored.

Option When it fits Cost When not to
Short-lived JWT access tokens APIs behind an IdP, microservices Refresh flow complexity When access must stop the instant it is revoked
JWT + jti deny-list Payments, admin APIs A cache lookup per request Low-risk, high-volume read APIs
Reference token + introspection Very sensitive APIs, partner access Network call per request (cache briefly) Latency-critical internal calls

Measure: chart 401s by failure reason; a sudden spike in SecurityTokenSignatureKeyNotFoundException points at key rollover or blocked JWKS fetches, not at attackers.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says JWTs can't be revoked Why: Checks they know the practical revocation options and their costs
    How to answer

    You can't change or recall a JWT once issued, so revocation means managing state outside the token. Keep access tokens short (5–15 minutes) and revoke the refresh token or session at the IdP, so no new access tokens are issued and access ends within one token lifetime. For immediate effect on high-risk APIs, keep a deny-list in Redis: revoked jti values with a TTL equal to the token's remaining lifetime, or a per-user 'tokens issued before' timestamp compared with iat, checked in JwtBearerEvents.OnTokenValidated (a sub-millisecond lookup; fail closed for admin and payment APIs). Microsoft Entra ID's Continuous Access Evaluation lets supported resources (for example Exchange Online, SharePoint and Graph, or your API if it implements claims challenges) reject tokens soon after events such as account disable or password reset. For the strictest cases, use reference tokens checked by introspection (RFC 7662).

  2. When: Candidate mentions the alg header Why: Checks awareness of classic JWT validation attacks
    How to answer

    Older JWT libraries chose the verification algorithm from the token's own alg header. With alg: none an attacker removed the signature and the library skipped verification. With RS256/HS256 confusion the attacker took the server's RSA public key (published in the JWKS), used its bytes as an HMAC secret to sign a forged token with alg: HS256, and a library that passed 'the key' to whatever algorithm the header named verified it successfully. Microsoft.IdentityModel ties algorithms to key types (an RsaSecurityKey can't be used to verify an HMAC signature), RequireSignedTokens (default true) rejects unsigned tokens, and you should pin ValidAlgorithms to what your issuer actually uses. Beyond that: get keys from the issuer's metadata rather than configuring them by hand, validate issuer and audience, and never write your own validation.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me