Description
Cookies without Secure may be sent over unencrypted HTTP, exposing sensitive values to interception or a man-in-the-middle attack.
Potential impact
- Information disclosure: Intercepted cookies may reveal sensitive values or allow session theft.
- Session hijacking: An attacker may use a captured session cookie to impersonate a user.
- Data tampering: Manipulated cookie values may affect application integrity.
Remediation
- Set
Secureso the browser sends the cookie only over HTTPS.
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.