Secure headers help protect your website from common attacks by telling browsers how to behave safely.
Secure headers configuration in 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.
response.headers['X-Frame-Options'] = 'DENY'
response.headers['Content-Security-Policy'] = "default-src 'self'"
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
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.
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)
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.
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.
Practice
Solution
Step 1: Understand Flask request lifecycle
Flask allows modifying responses after the view function runs using@app.after_request.Step 2: Identify where headers are added
Secure headers are added to the response object, which is accessible in@app.after_request.Final Answer:
The@app.after_requestdecorator -> Option CQuick Check:
Use@app.after_requestto add headers [OK]
@app.after_request for all responses [OK]- Using
@app.routewhich only defines routes - Trying to add headers in
@app.before_first_requestwhich runs once - Using
@app.teardown_requestwhich is for cleanup, not response modification
Solution
Step 1: Recall Flask response header syntax
Flask response headers are a dictionary-like object accessed viaresponse.headers.Step 2: Assign header value correctly
Useresponse.headers['Header-Name'] = valueto set or overwrite headers.Final Answer:
response.headers['Content-Security-Policy'] = "default-src 'self'" -> Option DQuick Check:
Headers set by assignment toresponse.headers[OK]
response.headers['Name'] = value to set headers [OK]- Using
headerinstead ofheaders - Trying to call
set_headerwhich Flask response lacks - Using
headers.addwhich is not a Flask method
X-Frame-Options header in the response?from flask import Flask, Response
app = Flask(__name__)
@app.after_request
def add_headers(response: Response):
response.headers['X-Frame-Options'] = 'DENY'
return response
@app.route('/')
def home():
return 'Hello'Solution
Step 1: Check header assignment in
The function sets@app.after_requestX-Frame-Optionsto 'DENY' on every response.Step 2: Confirm header presence in response
Since the header is set unconditionally, the response will haveX-Frame-Options: DENY.Final Answer:
'DENY' -> Option AQuick Check:
X-Frame-Optionsset to 'DENY' in after_request [OK]
@app.after_request apply to all responses [OK]- Assuming default header values without setting them
- Confusing
SAMEORIGINwithDENY - Thinking header is missing because not set in route
from flask import Flask
app = Flask(__name__)
@app.after_request
def secure_headers(response):
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
return response
@app.route('/')
def index():
return 'Welcome'Solution
Step 1: Review header name and value syntax
Header names are case-insensitive; using 'Strict-Transport-Security' is valid. The value is a valid string with quotes.Step 2: Check function signature and usage
@app.after_requestfunctions take one parameter (response) and return it. This matches the code.Final Answer:
No error; the code is correct -> Option BQuick Check:
Header added correctly in@app.after_request[OK]
- Thinking header names must be lowercase
- Expecting two parameters in after_request function
- Missing quotes around header value string
Solution
Step 1: Understand when headers should be added
Secure headers like Strict-Transport-Security should only be sent over HTTPS to avoid security risks.Step 2: Choose the best place to add headers conditionally
@app.after_requestruns after response creation and can accessrequest.is_secureto conditionally add headers efficiently for all routes.Step 3: Evaluate other options
Adding headers in each route duplicates code; setting headers globally without checking protocol risks sending them over HTTP;@app.before_requestcannot modify response headers.Final Answer:
Use@app.after_requestto checkrequest.is_secureand add headers conditionally -> Option AQuick Check:
Conditional header addition in@app.after_requestis best [OK]
request.is_secure in @app.after_request [OK]- Adding headers in each route causing repetition
- Sending secure headers over HTTP by default
- Trying to set headers in
@app.before_requestwhich can't modify response
Ready to prove it?
Pass the test and this pattern moves unknown
