What is a JWT
A JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are digitally signed, so the data they carry can be verified and trusted. They are widely used for authentication and authorization in web applications and APIs.
Structure of a JWT
A JWT consists of three Base64URL-encoded parts separated by dots: header.payload.signature.
- Header: token type ("JWT") and signature algorithm (e.g. HS256, RS256)
- Payload: claims — JSON data about the user and session (sub, exp, iat, roles, …)
- Signature: cryptographic hash of header + payload, signed with a secret or private key
Important: the payload is only encoded, not encrypted. Anyone can read the data inside. Never store sensitive information such as passwords in the payload.
Authentication flow
Upon login the server generates a JWT signed with a secret key and returns it to the client. On each subsequent request the client sends the JWT (typically in the Authorization: Bearer <token> header). The server verifies the signature and exp claim without hitting a database or session store.
Signature algorithms
- HS256 (HMAC-SHA256): symmetric — same secret used for signing and verification. Simple but secret must be shared between services.
- RS256 (RSA-SHA256): asymmetric — private key signs, public key verifies. Allows any service to verify tokens without knowing the private key.
- ES256 (ECDSA-SHA256): asymmetric with elliptic curves — shorter keys, same security as RS256, preferred in modern systems.
Security best practices
- Always set a short exp: 15 minutes for access tokens
- Use separate refresh tokens with rotation for long sessions
- Never put sensitive data in the payload: it is only Base64-encoded, not encrypted
- Store JWTs in HttpOnly + Secure + SameSite=Strict cookies to prevent XSS
- Invalidate compromised tokens with a revocation list (JTI deny-list) or rotate the secret key