Last active
February 18, 2019 18:56
-
-
Save srtab/19c7349a019467ed88c62b731581f991 to your computer and use it in GitHub Desktop.
Django X-Frame-Options to exempt or define same origin to third party applications by view name.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.middleware.clickjacking import XFrameOptionsMiddleware as DjangoXFrameOptionsMiddleware | |
class XFrameOptionsMiddleware(DjangoXFrameOptionsMiddleware): | |
""" | |
Wrapper into django.middleware.clickjacking.XFrameOptionsMiddleware to add extra x-frame-options exempt or same | |
origin by view name. | |
You can exempt views from third party applications, just define `XFRAME_OPTIONS_EXEMPT_PATTERNS` in your | |
settings with view name's: | |
``` | |
XFRAME_OPTIONS_EXEMPT_PATTERNS = ['oauth2_provider:authorize'] | |
``` | |
You can also define same origin to views from third party applications, just define `XFRAME_OPTIONS_SAMEORIGIN_PATTERNS` | |
in your settings with view name's: | |
``` | |
XFRAME_OPTIONS_SAMEORIGIN_PATTERNS = ['django_summernote-editor'] | |
``` | |
""" | |
def process_response(self, request, response): | |
if request.resolver_match: | |
if request.resolver_match.view_name in settings.XFRAME_OPTIONS_EXEMPT_PATTERNS: | |
response.xframe_options_exempt = True | |
if request.resolver_match.view_name in settings.XFRAME_OPTIONS_SAMEORIGIN_PATTERNS: | |
response.xframe_options_sameorigin = True | |
return super().process_response(request, response) | |
def get_xframe_options_value(self, request, response): | |
""" | |
Get the value to set for the X_FRAME_OPTIONS header. Use the value from the X_FRAME_OPTIONS setting, | |
or 'SAMEORIGIN' if not set, or even 'SAMEOIRGIN' if response comes with 'xframe_options_sameorigin' attribute | |
as True. | |
""" | |
if getattr(response, 'xframe_options_sameorigin', False): | |
return 'SAMEORIGIN' | |
return super().get_xframe_options_value(request, response) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment