What is JWT? — JSON Web Token Explained
Definition
JWT (JSON Web Token) is a compact, URL-safe token format for securely transmitting claims between parties. A JWT is a self-contained token: it carries all the information needed to verify it, including a digital signature, without requiring a database lookup. JWTs are widely used for stateless authentication in single-page applications and APIs, where the server issues a signed token that the client sends with every subsequent request.
How It Works
A JWT consists of three base64url-encoded parts separated by dots: header.payload.signature. The header contains the algorithm (e.g., HS256, RS256) and token type. The payload contains claims — statements about the user like user ID, roles, expiration time (exp), issued-at time (iat), and any custom data. The signature is computed by cryptographically signing the header and payload with a secret key (HMAC) or private key (RSA/ECDSA). The receiver verifies the token by recomputing the signature and comparing it; if they match, the payload has not been tampered with.
Common Use Cases
- ▸Issuing authentication tokens after login for stateless API authorization
- ▸Passing user identity between microservices without shared session state
- ▸Implementing single sign-on (SSO) where a token is trusted by multiple services
- ▸Short-lived access tokens in OAuth 2.0 flows
- ▸Encoding claims for email verification and password reset links
Example
Header: {"alg": "HS256", "typ": "JWT"}
Payload: {"sub": "1234567890", "name": "Alice", "iat": 1516239022, "exp": 1516242622}
Token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8URelated Tools
FAQ
- Is a JWT encrypted?
- A standard JWT (JWS — JSON Web Signature) is signed but not encrypted. The payload is only base64-encoded, meaning anyone can read it without the secret. Never put sensitive data like passwords or credit card numbers in a JWT payload unless you use JWE (JSON Web Encryption).
- How do I invalidate a JWT before it expires?
- Because JWTs are stateless, they cannot be invalidated server-side without maintaining a blocklist. Common approaches are: using very short expiration times (15 minutes) with refresh tokens, or maintaining a token blocklist in Redis for tokens that need to be revoked immediately.
- What is the difference between HS256 and RS256?
- HS256 (HMAC-SHA256) uses a shared secret key — both the issuer and verifier use the same key. RS256 (RSA-SHA256) uses an asymmetric key pair: the issuer signs with a private key and any verifier can check with the public key. RS256 is preferred when multiple services need to verify tokens without sharing a secret.