How to Set a SameSite Cookie in Python
Set a SameSite cookie attribute in Python using the standard library's SimpleCookie class.
Python code
12 linesfrom http.cookies import SimpleCookie
def set_same_site_cookie(name, value, same_site="Lax"):
cookie = SimpleCookie()
cookie[name] = value
cookie[name]["path"] = "/"
cookie[name]["samesite"] = same_site
return cookie[name].OutputString()
if __name__ == "__main__":
print(set_same_site_cookie("session_id", "abc123", "Strict"))
print(set_same_site_cookie("prefs", "dark_mode"))
Output
session_id=abc123; Path=/; SameSite=Strict
prefs=dark_mode; Path=/; SameSite=Lax
How it works
The SimpleCookie class from the http.cookies module provides a convenient way to construct HTTP cookie headers. Setting the samesite attribute ensures the cookie is only sent on same-site requests, which helps mitigate CSRF attacks. The OutputString() method returns the cookie in RFC 6265 format. Using the standard library avoids external dependencies and keeps the code portable. This is a building block for secure session handling in web applications.
Common mistakes
- Forgetting to set the `path` attribute, which can cause the cookie to be sent on unexpected paths.
- Using case-sensitive attribute names incorrectly (e.g., `SameSite` instead of `samesite`).
- Not validating the `same_site` value, allowing invalid values like 'None' or ' '.
Variations
- Use `SimpleCookie` to set multiple cookies at once, each with its own attributes.
- Set the `secure` and `httponly` flags in addition to `samesite` for enhanced security.
Real-world use cases
- Setting session cookies in web frameworks like Django or Flask by generating the Set-Cookie header manually.
- Configuring authentication cookies in API gateways to enforce CSRF protection across microservices.
- Implementing cookie-based consent banners where SameSite helps track user preferences safely.
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.