How To Protect Against CSRF [Cross-site Request Forgery ] Attacks

How To Protect Against CSRF [Cross-site Request Forgery ] Attacks

Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the website trusts. Learn more


To enable CSRF protection, add the CsrfViewMiddleware to your middleware classes. This middleware is enabled by default.


This middleware will set a token in a cookie on the outgoing response. Whenever an incoming request uses an unsafe method (any method except GETHEADOPTIONS and TRACE), the cookie must match a token that is send as the csrfmiddlewaretoken form data or as the X-CsrfToken header. This ensures that the client initiating the request is also the owner of the cookie and, by extension, the (authenticated) session.

If a request is made over HTTPS, strict referrer checking is enabled. If the HTTP_REFERER header does not match the host of the current request or a host in CSRF_TRUSTED_ORIGINS (new in 1.9), the request is denied.


Forms that use the POST method should include the CSRF token in the template. The {% csrf_token %} template tag will output a hidden field, and will ensure that the cookie is set on the response:

<form method='POST'>
{% csrf_token %}

Individual views that are not vulnerable to CSRF attacks can be made exempt using the @csrf_exempt decorator:

from django.views.decorators.csrf import csrf_exempt

def my_view(request, *args, **kwargs):
    """Allows unsafe methods without CSRF protection"""
    return HttpResponse(...)

Although not recommended, you can disable the CsrfViewMiddleware if many of your views are not vulnerable to CSRF attacks. In this case you can use the @csrf_protect decorator to protect individual views:

from django.views.decorators.csrf import csrf_protect

def my_view(request, *args, **kwargs):
    """This view is protected against CSRF attacks if the middleware is disabled"""
    return HttpResponse(...)


Similar Posts