What is JWT?
JWT (JSON Web Token, RFC 7519) is an open standard for securely transmitting information between parties as a JSON object. JWTs are commonly used for authentication and information exchange.
JWT Structure
A JWT consists of three parts separated by dots (.):
Header.Payload.Signature
1. Header
The header typically contains:
- alg: Signing algorithm, e.g.,
HS256,RS256,ES256 - typ: Token type, fixed as
JWT
2. Payload
The payload contains claims - the data being transmitted:
-
Registered Claims: Standard fields
sub(Subject): Usually user IDiss(Issuer)exp(Expiration Time)iat(Issued At)aud(Audience)nbf(Not Before)
-
Public Claims: Custom fields registered in IANA
-
Private Claims: Custom fields agreed between parties
3. Signature
The signature verifies the message hasn't been tampered with:
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
Security Warning
JWT Payload is Base64-encoded, not encrypted! Never store sensitive data like passwords or credit card numbers in a JWT.
Algorithm Selection
Symmetric (HS256/HS384/HS512)
- Same key for signing and verification
- Suitable for single-server apps
- Key must be kept secret
Asymmetric (RS256/ES256) — Recommended
- Private key signs, public key verifies
- Suitable for microservices
- Public keys can be safely distributed
Verification Checklist
- Signature verification using public key or shared secret
- exp (Expiration): Reject expired tokens
- nbf (Not Before): Reject future tokens
- iss (Issuer): Verify trusted issuer
- aud (Audience): Verify intended recipient
Token Lifecycle
- Access Token: 15-60 minute validity
- Refresh Token: 7-30 day validity with rotation
- Use Redis blacklist for emergency revocation
- Short expiration + refresh rotation is best practice