The cookies generated by a Flask application may not contain the Secure
and HttpOnly
flags. This can cause security issues.
Secure
flag: A secure cookie can only be transmitted over HTTPS connection.HttpOnly
flag: An http-only cookie cannot be accessed JavaScript.Secure
and HttpOnly
cookie flags in a Flask application¶If you use the cookie based session of Flask, you should update related configurations:
from flask import Flask
app = Flask(__name__)
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True
Every time you call response.set_cookie
method, you should pass in related parameters:
response.set_cookie(key, value, httponly=True, secure=True)
Secure
flag¶As we talked earlier, A secure cookie can only be transmitted over HTTPS connection. But when we develop our app, the app is usually hosted on a http server rather than a HTTPS server.
Instead of turning off the Secure
flag when developing, we have a better option: run the http server on localhost.
This works because Browsers (Firefox and latest Chrome) ignore the Secure
flag when the host is localhost
.