Understand JSON Web Tokens (JWT) - how they work, security best practices, and common vulnerabilities to avoid in authentication systems.
JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are digitally signed, making them trustworthy for authentication and information exchange.
A JWT consists of three parts separated by dots: Header, Payload, and Signature. The Header contains the algorithm and token type. The Payload contains claims like user ID, email, role, and timestamps. The Signature is created by signing the header and payload with a secret key.
The typical flow involves: user logs in with credentials, server validates credentials, server creates JWT with user info and expiry, client stores JWT, client sends JWT in Authorization header for subsequent requests, server verifies signature and checks expiry, then processes the request if valid.
HS256 uses symmetric keys with the same secret for signing and verification, best for single service or internal APIs. RS256 uses asymmetric cryptography with private key for signing and public key for verification, ideal for distributed systems. ES256 uses elliptic curve cryptography for smaller signatures, perfect for mobile apps.
Never store sensitive data in the payload since JWT is not encrypted, only Base64 encoded. Use short expiration times like 15 minutes for access tokens with refresh tokens for extended sessions. Validate everything including algorithms, issuer, and audience. Use 256-bit secrets minimum. Store tokens in HttpOnly cookies when possible for XSS protection.
The None Algorithm Attack exploits libraries that accept alg: none, allowing attackers to forge tokens. Weak secrets can be brute-forced, so use cryptographically secure random keys. Information leakage occurs because anyone can decode JWT payloads. Replay attacks can be prevented using the jti claim and maintaining blacklists.
JWT is a powerful tool for stateless authentication, but security depends on strong secrets, short expiry times, proper storage, algorithm restriction, and thorough claim validation. Never store passwords, credit cards, or personal information in the token payload.