5.2. HTTPS and Flask#
By default, Flask does not handle HTTPS on its own. Flask’s built-in development server is designed for local testing and does not provide production-grade HTTPS support. In a real deployment, a reverse proxy server such as NGINX, Apache, or a cloud provider’s load balancer is required to terminate HTTPS connections and forward requests to Flask.
5.2.1. Flask-Talisman#
Flask-Talisman is a security-focused extension for Flask that ensures all incoming requests use HTTPS and enforces HTTP Strict Transport Security (HSTS). While Flask-Talisman does not enable HTTPS itself, it ensures that all traffic is encrypted using HTTPS before being handled by Flask.
Flask-Talisman provides the following HTTPS related features:
In cases where a HTTP request reaches Talisman, it is redirected to HTTPS.
Enables HTTP Strict Transport Security .
Sets Flask’s session cookie to
secure, so it will never be set if your application is somehow accessed via a non-secure connection.
5.2.2. Setting up Flask-Talisman#
To wrap our Flask app securely with Flask-Talisman we just need to:
Import the
TalismanfunctionApply the
Talismanfunction to the Flask app object
A complete example is below:
from flask import Flask, request
from flask_talisman import Talisman
app = Flask(__name__)
Talisman(app) # Secure the app with Talisman
@app.route("/")
def home():
print("Hello World!")
app.run(debug=True, reloader_type="stat", port=5000)
Code Challenge: Enforce HTTPS
Secure the provided flask app by wrapping the app with flask-talisman.
You will need to:
Import the library
flask_talisman import Talisman
Wrap the app object
from flask import Flask, request from
Talisman(app)
Note
When you are successful, any HTTP requests made to the flask app will be automatically redirected to HTTPS requests and cookies will be served only over HTTPS.
Download the scaffold and write your code in app.py.
Solution
Solution is locked