← Back to Learn
JWT Flows
Understanding how JWTs are used in authentication and authorization flows is crucial for implementing secure applications.
Authentication Flow
- User Login: User provides credentials (username/password)
- Server Validation: Server validates credentials against database
- Token Generation: Server creates JWT with user information
- Token Response: Server sends JWT to client (usually in response body or cookie)
- Client Storage: Client stores token (localStorage, sessionStorage, or cookie)
- Subsequent Requests: Client includes JWT in Authorization header
- Token Verification: Server verifies signature and validates claims
- Access Granted: Server processes request if token is valid
Example API Flow
// Client sends credentials
POST /api/login
{
"username": "user",
"password": "pass"
}
// Server responds with JWT
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
// Client includes token in requests
GET /api/protected
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...Authorization Flow
Once authenticated, JWTs are used to authorize access to resources based on claims in the token.
- Request with Token: Client includes JWT in request
- Token Extraction: Server extracts token from Authorization header
- Signature Verification: Server verifies token signature
- Expiration Check: Server checks if token is expired
- Claim Validation: Server validates required claims (roles, permissions)
- Access Control: Server grants or denies access based on claims
Refresh Token Flow
For better security, use short-lived access tokens with long-lived refresh tokens.
- User logs in and receives both access token (short-lived) and refresh token (long-lived)
- Client uses access token for API requests
- When access token expires, client uses refresh token to get new access token
- Server validates refresh token and issues new access token
- Process repeats until refresh token expires
Token Storage Best Practices
✅ Recommended
- HttpOnly cookies for web applications
- Secure flag for HTTPS-only transmission
- SameSite attribute to prevent CSRF
❌ Avoid
- localStorage (vulnerable to XSS attacks)
- sessionStorage (cleared on tab close)
- URL parameters (visible in logs and browser history)