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.


Related Topics

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 minutes read.

Django Tutorial

Django Introduction It is a web application framework written in a python programming language. It based on the MVT( Model View Templet) design pattern. It takes a short time to build an application...

2 minutes read.

Django Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

3 minutes read.

Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website,...

3 minutes read.

Django Installation

Django Installation Django development environment consists of installing and setting up Python, Django, and a Database System since Django deals with a web application. Below the statement will guide you through installing Python 3.8.0 and...

2 minutes read.

Django Model

Django Model A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are...

6 minutes read.

Django Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Environment Setup

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. A framework is a collection of...

4 minutes read.

How to Implement Multiple User Types with Django

Django Framework: Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

3 minutes read.

Django DRF

Django Rest Framework, which is also referred to as DRF, is a very powerful application to build RESTful APIs in a Django application. DRF uses the Django framework. Similar to...

3 minutes read.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.

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,...

4 minutes read.

Django Authentication

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Best Django courses

In this tutorial, we will see various courses in python Django available on the internet. Django has become popular these days, so courses on it are also increasing day by...

7 minutes read.

Django Admin

To manage the content of the website, e.g., adding and deleting posts, web developers need an admin portal on the website. The admin portal allows trusted users, also knows as...

3 minutes read.