0
0
Flaskframework~30 mins

Secure headers configuration in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Secure headers configuration
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use the standard Flask pattern to run the app only when the script is executed directly.