| 1 |
""" |
| 2 |
Clickjacking Protection Middleware. |
| 3 |
|
| 4 |
This module provides a middleware that implements protection against a |
| 5 |
malicious site loading resources from your site in a hidden frame. |
| 6 |
""" |
| 7 |
|
| 8 |
from django.conf import settings |
| 9 |
from django.utils.deprecation import MiddlewareMixin |
| 10 |
|
| 11 |
|
| 12 |
class XFrameOptionsMiddleware(MiddlewareMixin): |
| 13 |
""" |
| 14 |
Set the X-Frame-Options HTTP header in HTTP responses. |
| 15 |
|
| 16 |
Do not set the header if it's already set or if the response contains |
| 17 |
a xframe_options_exempt value set to True. |
| 18 |
|
| 19 |
By default, set the X-Frame-Options header to 'DENY', meaning the response |
| 20 |
cannot be displayed in a frame, regardless of the site attempting to do so. |
| 21 |
To enable the response to be loaded on a frame within the same site, set |
| 22 |
X_FRAME_OPTIONS in your project's Django settings to 'SAMEORIGIN'. |
| 23 |
""" |
| 24 |
|
| 25 |
def process_response(self, request, response): |
| 26 |
# Don't set it if it's already in the response |
| 27 |
if response.get("X-Frame-Options") is not None: |
| 28 |
return response |
| 29 |
|
| 30 |
# Don't set it if they used @xframe_options_exempt |
| 31 |
if getattr(response, "xframe_options_exempt", False): |
| 32 |
return response |
| 33 |
|
| 34 |
response.headers["X-Frame-Options"] = self.get_xframe_options_value( |
| 35 |
request, |
| 36 |
response, |
| 37 |
) |
| 38 |
return response |
| 39 |
|
| 40 |
def get_xframe_options_value(self, request, response): |
| 41 |
""" |
| 42 |
Get the value to set for the X_FRAME_OPTIONS header. Use the value from |
| 43 |
the X_FRAME_OPTIONS setting, or 'DENY' if not set. |
| 44 |
|
| 45 |
This method can be overridden if needed, allowing it to vary based on |
| 46 |
the request or response. |
| 47 |
""" |
| 48 |
return getattr(settings, "X_FRAME_OPTIONS", "DENY").upper() |