How to Create Secure Session Cookies in Python with Secure, HttpOnly, and SameSite Flags
This code demonstrates how to create a secure session cookie using Python's stdlib, setting Secure, HttpOnly, and SameSite attributes to protect against common web vulnerabilities.
Python code
33 linesimport http.cookies
import secrets
class SessionManager:
def __init__(self):
self.cookie = http.cookies.SimpleCookie()
def create_session_cookie(self, session_id=None):
session_id = session_id or secrets.token_hex(16)
self.cookie["session"] = session_id
self.cookie["session"]["path"] = "/"
self.cookie["session"]["secure"] = True
self.cookie["session"]["httponly"] = True
self.cookie["session"]["samesite"] = "Lax"
return self.cookie.output(header="")
def mock_request(session_manager):
# Simulate server-side cookie response
cookie_header = session_manager.create_session_cookie()
print(f"Set-Cookie: {cookie_header}")
# Simulate client-side cookie retrieval
parsed = http.cookies.SimpleCookie()
parsed.load(cookie_header)
cookie = parsed["session"]
print(f"Session ID: {cookie.value}")
print(f"Secure: {cookie['secure']}")
print(f"HttpOnly: {cookie['httponly']}")
print(f"SameSite: {cookie['samesite']}")
if __name__ == "__main__":
manager = SessionManager()
mock_request(manager)
Output
Set-Cookie: session=<random-hex-32-chars>; HttpOnly; Path=/; SameSite=Lax; Secure
Session ID: <random-hex-32-chars>
Secure: True
HttpOnly: True
SameSite: Lax
How it works
The http.cookies.SimpleCookie class builds a cookie object where you can set attributes like secure, httponly, and samesite. Setting secure=True tells browsers to send the cookie only over HTTPS, preventing interception on plain HTTP. httponly=True blocks JavaScript access, mitigating XSS attacks that steal session tokens. The samesite="Lax" attribute limits cross-site requests, reducing CSRF risk. Using secrets.token_hex(16) generates a cryptographically strong session ID.
Common mistakes
- Forgetting to set `secure=True` in production behind HTTP, which leaks session cookies over unencrypted connections.
- Omitting `samesite` or setting it to `None`, which weakens CSRF defenses.
- Using `random` instead of `secrets` for session IDs, leading to predictable tokens.
- Not parsing the cookie header with `SimpleCookie.load()` when reading it back for testing or client simulation.
Variations
- Use `session_id = secrets.token_urlsafe(32)` for a URL-safe session token.
- Set `samesite="Strict"` for stricter CSRF protection in applications with same-site-only workflows.
Real-world use cases
- Creating session cookies in a Flask or Django web app and setting them on the response with flags for security.
- Generating secure session identifiers for a serverless authentication function before storing them in Redis or a database.
- Testing cookie attributes in an automated integration test to verify that HTTPS-only and HttpOnly flags are applied.
Sponsored
More from Auth & security at scale
- ACME LetsEncrypt Mock Challenge Server in Python medium
- AES GCM encryption and decryption in Python medium
- Build a Mock OIDC Userinfo Endpoint in Python with Flask easy
- ChaCha20-Poly1305 mock in Python medium
- ECDH key agreement in Python with cryptography medium
- Enforce TLS 1.2 Minimum in Python easy
Keep learning
Related tutorials and quizzes for this topic.