Skip to content

Commit 53e211f

Browse files
committed
implemented async-only clickjacking middleware
1 parent 33c52d1 commit 53e211f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
10+
from django_async_extensions.amiddleware.base import AsyncMiddlewareMixin
11+
12+
13+
class AsyncXFrameOptionsMiddleware(AsyncMiddlewareMixin):
14+
"""
15+
Set the X-Frame-Options HTTP header in HTTP responses.
16+
17+
Do not set the header if it's already set or if the response contains
18+
a xframe_options_exempt value set to True.
19+
20+
By default, set the X-Frame-Options header to 'DENY', meaning the response
21+
cannot be displayed in a frame, regardless of the site attempting to do so.
22+
To enable the response to be loaded on a frame within the same site, set
23+
X_FRAME_OPTIONS in your project's Django settings to 'SAMEORIGIN'.
24+
"""
25+
26+
async def process_response(self, request, response):
27+
# Don't set it if it's already in the response
28+
if response.get("X-Frame-Options") is not None:
29+
return response
30+
31+
# Don't set it if they used @xframe_options_exempt
32+
if getattr(response, "xframe_options_exempt", False):
33+
return response
34+
35+
response.headers["X-Frame-Options"] = self.get_xframe_options_value(
36+
request,
37+
response,
38+
)
39+
return response
40+
41+
def get_xframe_options_value(self, request, response):
42+
"""
43+
Get the value to set for the X_FRAME_OPTIONS header. Use the value from
44+
the X_FRAME_OPTIONS setting, or 'DENY' if not set.
45+
46+
This method can be overridden if needed, allowing it to vary based on
47+
the request or response.
48+
"""
49+
return getattr(settings, "X_FRAME_OPTIONS", "DENY").upper()

0 commit comments

Comments
 (0)