JWT Security

JWT structure, signature algorithms, validation checklist, common vulnerabilities (alg confusion, none, weak secrets), revocation strategies and where JWTs should not be used.

Structure

A JWT (RFC 7519) is base64url(header).base64url(payload).signature. Header specifies the algorithm (RS256, ES256, PS256, EdDSA) and key ID (kid). Payload contains claims: iss, sub, aud, exp, nbf, iat, jti, scope, custom claims. The signature (JWS) proves integrity, not confidentiality: anyone can read the payload. Use JWE if encryption is needed.

Validation checklist (for APIs)

  1. Accept only expected algorithms (e.g. RS256/ES256); never none; never let the token choose an HMAC algorithm when you expect RSA (algorithm confusion attack).
  2. Verify the signature with keys from the issuer's JWKS endpoint, matched by kid, cached with refresh.
  3. Check iss equals the trusted issuer.
  4. Check aud contains this API.
  5. Check exp and nbf with small clock skew.
  6. Check required scopes/roles for the operation.
  7. Enforce object-level authorization separately.
@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation("https://login.example.com")
        .jwsAlgorithm(SignatureAlgorithm.RS256).build();
    OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
        aud -> aud != null && aud.contains("orders-api"));
    decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
        JwtValidators.createDefaultWithIssuer("https://login.example.com"), audience));
    return decoder;
}

Common vulnerabilities

Issue Mitigation
alg: none accepted Library configuration with allowed algorithms
HS256 with weak shared secret Asymmetric keys; strong secrets if HMAC is required
Sensitive data in payload Payload is readable; keep claims minimal
Long expiry, no revocation Short-lived tokens; refresh rotation; denylist for emergencies
Token in URL or logs Authorization header only; redact logs
Storing tokens in browser localStorage XSS can steal them; prefer BFF with HttpOnly cookies

Revocation strategies

Short access-token lifetimes (5–15 minutes), revoke refresh tokens at the authorization server, jti denylist checked at the gateway for emergencies, or opaque tokens with introspection for high-security APIs.

Interview questions and answers

JWT or opaque tokens?

JWTs allow local validation (no call to the IdP per request) and scale well, but are hard to revoke instantly. Opaque tokens require introspection (latency, dependency) but are revocable and hide claims. Many systems use JWT access tokens with short TTL, and opaque refresh tokens.