Enhance the cookie security of a python Flask application

The cookies generated by a Flask application may not contain the Secure and HttpOnly flags. This can cause security issues.

Background information

  • Secure flag: A secure cookie can only be transmitted over HTTPS connection.
  • HttpOnly flag: An http-only cookie cannot be accessed JavaScript.

Session cookies

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

Custom cookies

Every time you call response.set_cookie method, you should pass in related parameters:

response.set_cookie(key, value, httponly=True, secure=True)

Development with 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.

This article is originally created by tooli.top. Please indicate the source when reprinting : https://www.tooli.top/posts/flask_cookie_security

Posted on 2023-03-07 Mail to author