← Back to Learn

JWT Flows

Understanding how JWTs are used in authentication and authorization flows is crucial for implementing secure applications.

Authentication Flow

  1. User Login: User provides credentials (username/password)
  2. Server Validation: Server validates credentials against database
  3. Token Generation: Server creates JWT with user information
  4. Token Response: Server sends JWT to client (usually in response body or cookie)
  5. Client Storage: Client stores token (localStorage, sessionStorage, or cookie)
  6. Subsequent Requests: Client includes JWT in Authorization header
  7. Token Verification: Server verifies signature and validates claims
  8. 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.

  1. Request with Token: Client includes JWT in request
  2. Token Extraction: Server extracts token from Authorization header
  3. Signature Verification: Server verifies token signature
  4. Expiration Check: Server checks if token is expired
  5. Claim Validation: Server validates required claims (roles, permissions)
  6. 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.

  1. User logs in and receives both access token (short-lived) and refresh token (long-lived)
  2. Client uses access token for API requests
  3. When access token expires, client uses refresh token to get new access token
  4. Server validates refresh token and issues new access token
  5. 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)