Security Best Practices
Cookies often hold sensitive data like login sessions, so set them carefully. The flags below tell the browser how a cookie may be used.
1. Cookie Flags
Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict
- HttpOnly: Prevents JavaScript access
- Secure: Only sent over HTTPS
- SameSite: Controls cross-site behavior
- Domain: Limits cookie scope
- Path: Restricts cookie access path
In short: HttpOnly hides the cookie from page scripts so a cross-site scripting attack cannot steal it; Secure sends it only over HTTPS (encrypted) connections; and SameSite limits whether it travels on requests coming from other sites.
2. Implementation Guidelines
# Secure cookie setting in Python/Flask
from flask import make_response
@app.route('/set-cookie')
def set_secure_cookie():
resp = make_response('Cookie set')
resp.set_cookie(
'user_id',
'abc123',
secure=True,
httponly=True,
samesite='Strict',
max_age=3600 # 1 hour
)
return resp
3. Privacy Considerations
- Implement cookie consent
- Respect user preferences
- Minimize data collection
- Follow GDPR guidelines
- Regular cookie cleanup
Debugging Tools
When cookies misbehave, inspect them from both sides: the browser (what the client stored) and the server (what it received).
1. Browser DevTools
// Console commands for cookie management
// List all cookies
console.log(document.cookie)
// Clear cookies
document.cookie.split(';').forEach(cookie => {
document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
});
2. Server-Side Inspection
# Flask route to inspect cookies
@app.route('/debug/cookies')
def debug_cookies():
return {
'cookies': request.cookies,
'session': dict(session),
'headers': dict(request.headers)
}
Remember: Always handle cookies with security in mind and respect user privacy preferences. Stay updated with the latest browser policies and privacy regulations regarding cookie usage.
