Django Clickjacking protection


Example

Clickjacking is a malicious technique of tricking a Web user into clicking on something different from what the user perceives they are clicking on. Learn more

To enable clickjacking protection, add the XFrameOptionsMiddleware to your middleware classes. This should already be there if you didn't remove it.

# settings.py
MIDDLEWARE_CLASSES = [
    ...
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ...
]

This middleware sets the 'X-Frame-Options' header to your all your responses, unless explicitly exempted or already set (not overridden if already set in the response). By default it is set to "SAMEORIGIN". To change this, use the X_FRAME_OPTIONS setting:

X_FRAME_OPTIONS = 'DENY'

You can override the default behaviour on a per-view basis.

from django.utils.decorators import method_decorator
from django.views.decorators.clickjacking import (
    xframe_options_exempt, xframe_options_deny, xframe_options_sameorigin,
)

xframe_options_exempt_m = method_decorator(xframe_options_exempt, name='dispatch')

@xframe_options_sameorigin
def my_view(request, *args, **kwargs):
    """Forces 'X-Frame-Options: SAMEORIGIN'."""
    return HttpResponse(...)

@method_decorator(xframe_options_deny, name='dispatch')
class MyView(View):
    """Forces 'X-Frame-Options: DENY'."""

@xframe_options_exempt_m
class MyView(View):
    """Does not set 'X-Frame-Options' header when passing through the
    XFrameOptionsMiddleware.
    """