📖 Scenario: You are building a simple Flask web application that needs to be more secure by adding HTTP headers that protect users from common web attacks.These headers help browsers understand how to handle your site safely.
🎯 Goal: Configure your Flask app to send secure HTTP headers with every response.This will include setting headers like Content-Security-Policy, X-Content-Type-Options, and Strict-Transport-Security.
📋 What You'll Learn
Create a basic Flask app with one route
Add a configuration variable for the Content Security Policy
Use a function to add secure headers to all responses
Ensure the app sends the secure headers correctly
💡 Why This Matters
🌍 Real World
Web applications need to send secure headers to protect users from attacks like cross-site scripting and clickjacking.
💼 Career
Knowing how to configure secure headers in Flask is important for backend developers to build safer web services.
Progress0 / 4 steps
1
Create a basic Flask app with one route
Write code to import Flask from flask, create an app called app, and add a route / that returns the string 'Hello, secure world!'.
Flask
Hint
Remember to define a function called home decorated with @app.route('/') that returns the greeting string.
2
Add a configuration variable for the Content Security Policy
Add a variable called CONTENT_SECURITY_POLICY and set it to the string "default-src 'self'" to define a simple content security policy.
Flask
Hint
Define CONTENT_SECURITY_POLICY exactly as shown to specify allowed content sources.
3
Use a function to add secure headers to all responses
Create a function called add_secure_headers decorated with @app.after_request that takes a response parameter. Inside it, set these headers on response.headers: 'Content-Security-Policy' to CONTENT_SECURITY_POLICY, 'X-Content-Type-Options' to 'nosniff', and 'Strict-Transport-Security' to 'max-age=31536000; includeSubDomains'. Finally, return the response.
Flask
Hint
Use @app.after_request to modify all responses and add the security headers.
4
Ensure the app sends the secure headers correctly
Add the code to run the Flask app only if the script is run directly by checking if __name__ == '__main__' and call app.run(debug=True) inside that block.
Flask
Hint
Use the standard Flask pattern to run the app only when the script is executed directly.
Practice
(1/5)
1. Which Flask feature is commonly used to add secure headers to every response?
easy
A. The @app.before_first_request decorator
B. The @app.route decorator
C. The @app.after_request decorator
D. The @app.teardown_request decorator
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_request decorator -> Option C
Quick Check:
Use @app.after_request to add headers [OK]
Hint: Add headers in @app.after_request for all responses [OK]
Common Mistakes:
Using @app.route which only defines routes
Trying to add headers in @app.before_first_request which runs once
Using @app.teardown_request which is for cleanup, not response modification
2. Which of the following is the correct syntax to add a Content-Security-Policy header in Flask?
easy
A. response.set_header('Content-Security-Policy', "default-src 'self'")
B. response.header['Content-Security-Policy'] = "default-src 'self'"
C. response.headers.add('Content-Security-Policy', "default-src 'self'")
D. response.headers['Content-Security-Policy'] = "default-src 'self'"
Solution
Step 1: Recall Flask response header syntax
Flask response headers are a dictionary-like object accessed via response.headers.
Step 2: Assign header value correctly
Use response.headers['Header-Name'] = value to set or overwrite headers.
Final Answer:
response.headers['Content-Security-Policy'] = "default-src 'self'" -> Option D
Quick Check:
Headers set by assignment to response.headers [OK]
Hint: Use response.headers['Name'] = value to set headers [OK]
Common Mistakes:
Using header instead of headers
Trying to call set_header which Flask response lacks
Using headers.add which is not a Flask method
3. Given this Flask code snippet, what will be the value of the X-Frame-Options header in the response?
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_request functions take one parameter (response) and return it. This matches the code.
Final Answer:
No error; the code is correct -> Option B
Quick Check:
Header added correctly in @app.after_request [OK]
Hint: Check function signature and header syntax carefully [OK]
Common Mistakes:
Thinking header names must be lowercase
Expecting two parameters in after_request function
Missing quotes around header value string
5. You want to add multiple secure headers in Flask, but only for HTTPS requests. Which is the best way to do this securely and efficiently?
hard
A. Use @app.after_request to check request.is_secure and add headers conditionally
B. Add headers in each route function only if request.scheme == 'https'
C. Set headers globally without checking protocol, assuming HTTPS everywhere
D. Use @app.before_request to add headers before response is created
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_request runs after response creation and can access request.is_secure to 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_request cannot modify response headers.
Final Answer:
Use @app.after_request to check request.is_secure and add headers conditionally -> Option A
Quick Check:
Conditional header addition in @app.after_request is best [OK]
Hint: Check request.is_secure in @app.after_request [OK]
Common Mistakes:
Adding headers in each route causing repetition
Sending secure headers over HTTP by default
Trying to set headers in @app.before_request which can't modify response
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.