Django CSRF

Django is a high-level python based web framework. Django is open source and free to use for all. Django provides many features to web developers like scalability, security, rapid development, etc. Developers use Django to reduce the hassle of web development. Django is used for both front-end and back-end development.

Security is one of the most important needs of the website. It is much easier to make a website without implementing security measures. We often skip the security in development versions or while we are making websites for college projects.

But when a website is deployed, the security measures are a must; otherwise, it could easily become a target of hackers or getting attacks from malicious requests.

Many security attacks can cause harm to a website. Cross-site request forgery is one of them. Django provides several ways to handle CSRF, and in this post, we will discuss some of them.

What is CSRF?

CSRF stands for cross-site request forgery. It is done by some malicious users on a site. CSRF refers to send requests from some malicious site pretending to be the original website. CSRF works on the user’s identity stored in cookies.
When a user visits the malicious website mistakenly thinking it is some other website and does some action on it, that website uses the cookie stored in the browser to do the action on behalf of the user.

Example

Suppose you visited your bank website and login to that website with your credentials. The browser will save a cookie with your credentials. Now suppose, you clicked on a malicious website unknowingly. That website has some code that makes the request to transfer money.

Since your browser already has saved the cookie with the required credentials, the bank will think it is the real request, and then they will process it. This will result in a loss of money. Henceforth CSRF is a serious threat to security, and it must be handled accurately on a website.

Every framework deals with CSRF differently. In Django, the server provides a CSRF token to handle CSRF attacks.

Django generated a CSRF token and sent it to the client. Whenever a client sends a request, the CSRF token also gets sent along with the header. If the CSRF token matches the server-generated token, then only the server will process the request. This token is kept safe from the attackers by the Same Origin Policy.

Using CSRF protection

Django provides a middleware to protect against Cross-Site Requests Forgery. Middleware is a set of functions that executes during the request and response process.

Step 1:

To use the CSRF protection middleware, create a project and then go to the settings.py file in your project directory, where you will find that CSRF middleware is activated by default in the MIDDLEWARE section of the file.

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Suppose we want to add any other middleware to our project. In that case, we have to declare 'django.middleware.csrf.CsrfViewMiddleware'middleware before any middleware that needs security and assumes that CSRF actions are taken care of.

If, for any reason, the CSRF middleware is disabled, then we can also use csrf_protect() on a particular view.

Step 2:

Django also provides a template tag to use CSRF tokens anywhere in the code without any difficulty. This token can be used in any form, which is of method POST only if the form is for an internal URL.

Syntax:

{% csrf_token %}

Step 3:

While creating the view for the template which uses the CSRF token, we have to ensure that the RequestContextis issued to render the response. We are not required to use RequestContext to render our views with render() or contrib apps because they already use RequestContext.

Decorator csrf_protect()

As mentioned above in step 2, if we do not want to cover up our whole application with 'django.middleware.csrf.CsrfViewMiddleware' middleware, but only to a particular view, then we can use the csrf_protect() decorator, which provides the same functionality as the middleware.

Note – The decorator must be used on all the views which are assigning CSRF token to the output and to that which are taking data from the forms. Also, using the middleware is recommended because if you forgot to use the decorator in a view, it would create issues.

Example:

Csrf_protect(view):

fromdjango.shortcuts import render 
fromdjango.views.decorators.csrf import csrf_protect


@csrf_protect
defsecure_view(request):     
var = {}     
    # ...     
return render(request, "new_view.html", var)

Working

A CSRF token is an alphanumeric code to which other users or sites do not have access.

This token is set by the middleware 'django.middleware.csrf.CsrfViewMiddleware'. The token is also masked with a key for security purposes. This key changes every time for a new user.

A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests. This value is also an alphanumeric code with a key.

When an incoming request like PUT, POST, or DELETE comes in, it must have a csrfmiddleware token in it, and this token must be correct; otherwise, the user will get a 403 error.