0
0
Flaskframework~5 mins

Secure headers configuration in Flask

Choose your learning style9 modes available
Introduction

Secure headers help protect your website from common attacks by telling browsers how to behave safely.

When you want to stop attackers from running harmful scripts on your site.
When you want to prevent your site from being shown inside other sites (clickjacking).
When you want to control which resources (like images or scripts) your site can load.
When you want to make sure browsers only use secure connections.
When you want to improve your website's overall security easily.
Syntax
Flask
from flask import Flask, make_response

app = Flask(__name__)

@app.after_request
def set_secure_headers(response):
    response.headers['Content-Security-Policy'] = "default-src 'self'"
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
    response.headers['Referrer-Policy'] = 'no-referrer'
    return response

The @app.after_request decorator lets you add headers to every response.

Headers are set by adding key-value pairs to response.headers.

Examples
This header stops your site from being shown inside frames on other sites.
Flask
response.headers['X-Frame-Options'] = 'DENY'
This header allows loading resources only from your own site.
Flask
response.headers['Content-Security-Policy'] = "default-src 'self'"
This header tells browsers to always use HTTPS for your site and its subdomains for one year.
Flask
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
Sample Program

This Flask app adds important security headers to every response to protect users and the site.

Visit the home page to see the content, and check browser DevTools to see the headers.

Flask
from flask import Flask, make_response

app = Flask(__name__)

@app.after_request
def set_secure_headers(response):
    response.headers['Content-Security-Policy'] = "default-src 'self'"
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
    response.headers['Referrer-Policy'] = 'no-referrer'
    return response

@app.route('/')
def home():
    return '<h1>Welcome to Secure Flask App</h1>'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Use browser DevTools (Network tab) to check if headers are correctly set.

Be careful with Content-Security-Policy; too strict rules can block needed resources.

Always test your site after adding headers to avoid breaking functionality.

Summary

Secure headers help protect your site from attacks by guiding browser behavior.

Flask lets you add headers easily using @app.after_request.

Common headers include Content-Security-Policy, X-Frame-Options, and Strict-Transport-Security.