How to Set X-Frame-Options DENY in Flask with a Mock Response
Set the X-Frame-Options header to DENY in a Flask response to prevent clickjacking, and verify it with Flask's test client.
pip install flask
Python code
15 linesfrom flask import Flask, Response
app = Flask(__name__)
@app.route("/")
def index():
response = Response("Hello, World!")
response.headers["X-Frame-Options"] = "DENY"
return response
if __name__ == "__main__":
with app.test_client() as client:
resp = client.get("/")
print(resp.get_data(as_text=True))
print(resp.headers.get("X-Frame-Options"))
Output
Hello, World!
DENY
How it works
The @app.route decorator registers the index function to handle GET requests to /. Inside, a Response object is created with the body string. Setting response.headers['X-Frame-Options'] = 'DENY' adds the HTTP header that instructs browsers not to render the page inside any frame or iframe, mitigating clickjacking attacks. The with app.test_client() block simulates a request without running a live server. client.get('/') returns a response object whose body and headers we print, confirming the header is present.
Common mistakes
- Setting the header after returning the response, which has no effect.
- Forgetting to import `Response` from flask or using `make_response` incorrectly.
- Testing against a live server instead of using the test client for unit tests.
Variations
- Use `app.after_request` to add the header globally to all responses.
- Set the header with a decorator on the route function using `make_response`.
Real-world use cases
- Protecting login pages and admin panels from clickjacking attacks.
- Compliance with security headers policies across a web application.
- Testing middleware that adds security headers in CI/CD pipelines.
Sponsored
More from Auth & security at scale
- ACME LetsEncrypt Mock Challenge Server in Python medium
- AES GCM encryption and decryption in Python medium
- Build a Mock OIDC Userinfo Endpoint in Python with Flask easy
- ChaCha20-Poly1305 mock in Python medium
- ECDH key agreement in Python with cryptography medium
- Enforce TLS 1.2 Minimum in Python easy
Keep learning
Related tutorials and quizzes for this topic.