JWT & OAuth2
JWT — Structure, Signing, Verification, and Expiry
Header, payload, signature specifications and JSON Web Keys (JWK).
Introduction
JSON Web Tokens (JWT) are an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. Since JWTs are digitally signed, the recipient can verify the token's authenticity and integrity independently without storing session states or querying databases.
Why It Matters
Traditional stateful sessions require servers to maintain session details in memory or cache databases, creating scale limitations. In contrast, JWT acts as a stateless, portable token containing all necessary user claims. The backend API validates the token cryptographically on every incoming request. This design is highly optimal for microservices, single page applications (SPAs), and cross-domain identity sharing.
Real-World Analogy
Think of a JWT like a certified letter of authorization bearing an official wax seal. When you show the letter to a security guard, they don't need to call the issuing government agency to verify your credentials. They simply look at the wax seal (Signature), verify it matches the agency's official stamp design, confirm the expiration date written in the text is still valid, and let you pass.
Detailed Mechanics
1. Structure of a JWT
A JWT is represented as a single compact string of three Base64URL-encoded JSON parts separated by dots (.): Header.Payload.Signature.
- Header: Specifies the metadata of the token, containing the token type (JWT) and the signing algorithm (e.g. HS256, RS256).
- Payload: Contains the claims. Claims are statements about the user and additional context data. Standard claims include
sub(subject/user identifier),iat(issued at timestamp), andexp(expiration timestamp). - Signature: The cryptographic hash created by signing the base64-encoded header and payload using a secret key (symmetric) or a private key (asymmetric).
2. Token Signing and Verification
Authentication servers sign tokens to guarantee integrity:
- Symmetric (HMAC): A single secret key is shared between the auth server (signer) and resource server (verifier). Easy to configure but requires distributing the secret key.
- Asymmetric (RSA/ECDSA): The auth server signs the token using its private key. The resource server verifies the signature using the corresponding public key. Security keys are often exposed dynamically via JSON Web Key Sets (JWKS) endpoints (e.g.
/.well-known/jwks.json).
3. Expiration and Revocation
Because JWTs are stateless, they cannot easily be revoked before expiration. To minimize exposure if a token is stolen, developers implement short-lived Access Tokens (e.g., 15 minutes) paired with long-lived Refresh Tokens stored securely in HTTP-only cookies. To force immediate revocation, servers check incoming token IDs against a Redis-based blacklist.
Practical Example
The structure of a JWT can be decoded easily. Below is a representation of the three sections of a JWT:
Quick Quiz
Q1: Can anyone read the user data inside a standard JWT payload sent over the network?
A) No, because JWTs are always encrypted.
B) Yes, because a standard JWT is only base64URL-encoded (which is reversible), not encrypted. Sensitive information should never be stored inside the payload unless the token is encrypted (JWE).
C) Only the server that has the secret key can read it.
D) The payload can only be decoded by Google Chrome browsers.
Answer: B — Base64URL encoding is easily decoded by any client. JWTs protect against tampering (via signature), not reading.
Q2: What happens if an attacker modifies the username claim in the payload of a JWT?
A) The token updates its signature automatically.
B) The server will accept it anyway if the expiration date is valid.
C) The server's validation check fails because the signature recalculated using the modified payload does not match the signature sent in the token header.
D) The browser will block the user's internet connection.
Answer: C — The signature is calculated from the header and payload. Any change to either section invalidates the signature.
Scenario-Based Challenge
Production Scenario:
A security audit reveals that your backend microservice validates JWTs simply by parsing the token claims using the Jwts.parser() library without setting a signing key. What vulnerability does this expose, and how is it resolved?
This exposes a severe **Signature Bypass vulnerability**. If no signing key is configured on the parser, attackers can construct a token with the header algorithm set to "none" and submit modified payloads. The parser accepts the token as valid because no signature validation is executed.
To resolve this:
- Configure the JWT parser bean to mandate verification keys: always call
setSigningKey(secretKey)orsetSigningKey(publicKey). - Enforce rejection of tokens signed with the
"none"algorithm during parsing configuration.
Interview Questions
1. Conceptual: What is the difference between an Access Token and a Refresh Token?
An Access Token is short-lived (e.g. 15 minutes) and is sent directly in API headers to authorize requests. A Refresh Token is long-lived (e.g. 7 days) and is kept securely on the client (or HTTP-only cookie). When the access token expires, the client submits the refresh token to the auth server to obtain a new access token without forcing the user to log in again.
2. Concept: How do you verify JWTs securely in a distributed system without introducing a single point of failure?
Use asymmetric key signing. The authorization server signs JWTs using its private key and exposes public keys via JWKS endpoints. Individual APIs fetch the public keys periodically, caching them locally to verify token signatures offline. No call to the auth database is needed per request.
Production Considerations
Use cryptographic signature algorithms with appropriate key lengths (minimum 256 bits for HMAC-SHA256, minimum 2048 bits for RSA). Always validate the exp (expiration) and iss (issuer) claims. Set up secure cookie parameters (Secure, HttpOnly, SameSite=Strict) when passing tokens back to browser-based clients.