1
---
2
name: session-management
3
description: >
4
Implement secure session management systems with JWT tokens, session storage,
5
token refresh, logout handling, and CSRF protection. Use when managing user
6
authentication state, handling token lifecycle, and securing sessions.
7
---
8
9
# Session Management
10
11
## Table of Contents
12
13
- [Overview](#overview)
14
- [When to Use](#when-to-use)
15
- [Quick Start](#quick-start)
16
- [Reference Guides](#reference-guides)
17
- [Best Practices](#best-practices)
18
19
## Overview
20
21
Implement comprehensive session management systems with secure token handling, session persistence, token refresh mechanisms, proper logout procedures, and CSRF protection across different backend frameworks.
22
23
## When to Use
24
25
- Implementing user authentication systems
26
- Managing session state and user context
27
- Handling JWT token refresh cycles
28
- Implementing logout functionality
29
- Protecting against CSRF attacks
30
- Managing session expiration and cleanup
31
32
## Quick Start
33
34
Minimal working example:
35
36
```python
37
# Python/Flask Example
38
from flask import current_app
39
from datetime import datetime, timedelta
40
import jwt
41
import os
42
43
class TokenManager:
44
def __init__(self, secret_key=None):
45
self.secret_key = secret_key or os.getenv('JWT_SECRET')
46
self.algorithm = 'HS256'
47
self.access_token_expires_hours = 1
48
self.refresh_token_expires_days = 7
49
50
def generate_tokens(self, user_id, email, role='user'):
51
"""Generate both access and refresh tokens"""
52
now = datetime.utcnow()
53
54
# Access token
55
access_payload = {
56
'user_id': user_id,
57
'email': email,
58
'role': role,
59
'type': 'access',
60
'iat': now,
61
'exp': now + timedelta(hours=self.access_token_expires_hours)
62
// ... (see reference guides for full implementation)
63
```
64
65
## Reference Guides
66
67
Detailed implementations in the `references/` directory:
68
69
| Guide | Contents |
70
|---|---|
71
| [JWT Token Generation and Validation](references/jwt-token-generation-and-validation.md) | JWT Token Generation and Validation |
72
| [Node.js/Express JWT Implementation](references/nodejsexpress-jwt-implementation.md) | Node.js/Express JWT Implementation |
73
| [Session Storage with Redis](references/session-storage-with-redis.md) | Session Storage with Redis |
74
| [CSRF Protection](references/csrf-protection.md) | CSRF Protection |
75
| [Session Middleware Chain](references/session-middleware-chain.md) | Session Middleware Chain |
76
| [Token Refresh Endpoint](references/token-refresh-endpoint.md) | Token Refresh Endpoint |
77
| [Session Cleanup and Maintenance](references/session-cleanup-and-maintenance.md) | Session Cleanup and Maintenance |
78
79
## Best Practices
80
81
### ✅ DO
82
83
- Use HTTPS for all session transmission
84
- Implement secure cookies (httpOnly, sameSite, secure flags)
85
- Use JWT with proper expiration times
86
- Implement token refresh mechanism
87
- Store refresh tokens securely
88
- Validate tokens on every request
89
- Use strong secret keys
90
- Implement session timeout
91
- Log authentication events
92
- Clear session data on logout
93
- Use CSRF tokens for state-changing requests
94
95
### ❌ DON'T
96
97
- Store sensitive data in tokens
98
- Use short secret keys
99
- Transmit tokens in URLs
100
- Ignore token expiration
101
- Reuse token secrets across environments
102
- Store tokens in localStorage (use httpOnly cookies)
103
- Implement session without HTTPS
104
- Forget to validate token signatures
105
- Expose session IDs in logs
106
- Use predictable session IDs
107