0
0
Djangoframework~5 mins

Clickjacking protection in Django

Choose your learning style9 modes available
Introduction

Clickjacking protection stops bad websites from tricking users into clicking hidden buttons on your site. It keeps your site safe and users confident.

When you want to prevent other sites from embedding your pages in frames or iframes.
When you want to protect sensitive actions like submitting forms or changing settings.
When you want to improve your website's security against UI redress attacks.
When you want to ensure your site content is only shown in trusted contexts.
Syntax
Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # other middleware
]

# Or in views:
from django.views.decorators.clickjacking import xframe_options_deny

@xframe_options_deny
def my_view(request):
    # view code
    pass

The XFrameOptionsMiddleware adds headers to block framing by default.

You can also use decorators like @xframe_options_deny on specific views.

Examples
This enables clickjacking protection site-wide by adding the X-Frame-Options header.
Django
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # other middleware
]
This disables framing only for the my_view view.
Django
from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_deny

@xframe_options_deny
def my_view(request):
    return HttpResponse('No framing allowed')
This allows framing only from the same site, blocking others.
Django
from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_sameorigin

@xframe_options_sameorigin
def my_view(request):
    return HttpResponse('Allowed only from same origin')
Sample Program

This simple Django view returns a message and denies any framing to protect against clickjacking.

Django
from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_deny

@xframe_options_deny
def home(request):
    return HttpResponse('Welcome to safe site!')
OutputSuccess
Important Notes

Remember to add 'django.middleware.clickjacking.XFrameOptionsMiddleware' to your MIDDLEWARE list for site-wide protection.

You can choose different headers like DENY, SAMEORIGIN, or allow framing selectively with decorators.

Test your site in browser DevTools Network tab to see the X-Frame-Options header in responses.

Summary

Clickjacking protection stops other sites from embedding your pages in frames.

Use Django's middleware or decorators to add the right headers easily.

This helps keep your users safe from hidden click tricks.