JWT — Cheat Sheet

Tags: jwt, authentication, authorization, security, token, web

Level: intermediate

TL;DR: JSON Web Tokens are stateless, self-contained mechanisms for securely transmitting information between parties as a JSON object, primarily used for authentication and API authorization.

Key concepts

Consists of three parts separated by dots: Header, Payload, and Signature.

Header defines the token type and the signing algorithm used, such as HMAC SHA256 or RSA.

Payload contains claims, which are statements about the user and additional metadata.

Claims are categorized into three types: registered, public, and private claims.

Signature ensures the token has not been altered in transit and verifies the issuer.

JWTs are stateless, meaning the server can validate the token without querying a database.

Tokens are Base64Url encoded, not encrypted, meaning anyone can decode and read the payload.

Typical questions and ready answers

Q: How do you handle JWT revocation if the tokens are stateless?R: I rely on short-lived access tokens paired with refresh tokens, or I implement a token blocklist in a fast cache like Redis for immediate invalidation.

Q: Where is the safest place to store a JWT on the client side?R: I prefer storing them in HttpOnly, Secure cookies to prevent XSS attacks from accessing the token, while using CSRF protection for requests.

Q: What is the difference between symmetric and asymmetric signing in JWT?R: Symmetric uses a single shared secret for both signing and verifying, while asymmetric uses a private key to sign and a public key to verify.

Pitfalls and common mistakes

Storing sensitive data like plain-text passwords or PII in the payload, which is easily readable.

Failing to reject tokens that specify the none algorithm in the header, bypassing signature checks.

Ignoring standard claim validation, such as checking token expiration (exp) or the expected issuer (iss).

Using excessively long expiration times for access tokens, increasing the window of opportunity if compromised.

Leaking the symmetric signing secret, which allows attackers to forge valid tokens for any user.

Snippets and commandsJavaScript

// Signing a token
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123, role: 'admin' }, 'your-256-bit-secret', { expiresIn: '15m' });

// Verifying a token
try {
  const decoded = jwt.verify(token, 'your-256-bit-secret');
  console.log(decoded.userId);
} catch (err) {
  // Handles TokenExpiredError, JsonWebTokenError, etc.
  console.error('Invalid token');
}
Jarvis Interviews
Jarvis