Description
Without Secure, the browser may send a sensitive cookie in an unencrypted HTTP request. Anyone who can observe that traffic may read its value.
Potential impact
An intercepted cookie may disclose sensitive data or, if it is a session cookie, allow someone to impersonate the user. Altered cookie values can also affect application data if the application trusts them.
Remediation
Restrict cookie transmission to HTTPS using the setting for your framework.
- In Django, set
SESSION_COOKIE_SECUREandCSRF_COOKIE_SECUREtoTrue. - For Flask session cookies, set
SESSION_COOKIE_SECURE=True. - In FastAPI, pass
secure=Truetoset_cookiewhen issuing a sensitive cookie.
Examples
Django cookie settings
Before
python
# Django cookie settings without the flag
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
After
python
# Django cookie settings with the flag
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
Flask cookie settings
Before
python
# Flask cookie settings without the flag
from flask import Flask
app = Flask(__name__)
app.config.update(
SESSION_COOKIE_SECURE=False,
)
After
python
# Flask cookie settings with the flag
from flask import Flask
app = Flask(__name__)
app.config.update(
SESSION_COOKIE_SECURE=True,
)
FastAPI cookie settings
Before
python
# FastAPI cookie settings without the flag
from fastapi import FastAPI, Response
import secrets
app = FastAPI()
@app.post("/set-cookie")
async def set_cookie(response: Response):
session_id = secrets.token_urlsafe(32) # An unpredictable session value issued by the server
response.set_cookie(
key="session",
value=session_id,
secure=False,
httponly=True,
samesite="lax",
)
return {"message": "Cookie set"}
After
python
# FastAPI cookie settings with the flag
from fastapi import FastAPI, Response
import secrets
app = FastAPI()
@app.post("/set-cookie")
async def set_cookie(response: Response):
session_id = secrets.token_urlsafe(32) # An unpredictable session value issued by the server
response.set_cookie(
key="session",
value=session_id,
secure=True,
httponly=True,
samesite="lax",
)
return {"message": "Cookie set"}
Explanation
- Before: Without
Secure, the cookie may be sent over HTTP. - After:
Securerestricts transmission to HTTPS.HttpOnlyseparately prevents JavaScript from reading the cookie.