What is JWT
JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact and self-contained way to securely transmit information between parties as a JSON object. This information can be verified and trusted because it's digitally signed.
Structure of a JWT
A JWT consists of three parts separated by dots (.):
xxxxx.yyyyy.zzzzz
1. Header
Contains metadata about the token:
Type of token (typically "JWT")
Signing algorithm used (e.g., HMAC SHA256, RSA)
{ "alg": "HS256", "typ": "JWT" }
2. Payload
Contains the claims (statements about an entity and additional data):
Registered claims: Predefined claims like
iss(issuer),exp(expiration time),sub(subject)Public claims: Custom claims defined by users
Private claims: Custom claims shared between parties
{ "sub": "1234567890", "name": "John Doe", "admin": true, "iat": 1516239022 }
3. Signature
Created by encoding the header and payload, then signing them with a secret key:
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
How JWT Works
Authentication Flow
User logs in with credentials
Server validates credentials and generates a JWT
Server returns the JWT to the client
Client stores the JWT (usually in localStorage or cookies)
Client includes JWT in subsequent requests (typically in Authorization header)
Server verifies the JWT signature and grants access
Example Request
GET /api/protected Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Key Characteristics
✅ Advantages
Stateless: Server doesn't need to store session information
Compact: Can be sent via URL, POST parameter, or HTTP header
Self-contained: Contains all necessary user information
Secure: Can be signed and optionally encrypted
Cross-domain: Works well with CORS and multiple domains
❌ Limitations
Cannot revoke: Once issued, tokens remain valid until expiration
Size: Can become large with many claims
Storage: Must be stored securely on client side
Common Use Cases
Authentication: Single sign-on (SSO), stateless sessions
Authorization: Access control for APIs and resources
Information Exchange: Securely transmitting data between parties
Security Best Practices
Use HTTPS always
Set short expiration times (e.g., 15 minutes)
Store securely (HttpOnly cookies for web apps)
Validate signature on every request
Use strong secrets for signing
Include minimal data in payload (avoid sensitive info)