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

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 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 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 Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

3 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 REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

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.

Django – Sending E-mails

Django – Sending E-mails Django comes with a light engine that is ready and simple to use to send emails. Similar to Python, you just need to import a smtplib. You just need to import django.core.mail in Django. Edit the project settings.py file to start sending emails and set  all the following options: EMAIL_HOST – server with smtp.EMAIL_HOST_USER – smtp server login key.EMAIL_HOST_PASSWORD ? Password credential for the smtp server.EMAIL_PORT – server port smtp.EMAIL_USE_TLS or _SSL – if it is secure connection then set True. Simple E-mail Sending To submit a simple e-mail, let's create it a "simpleEmail" view. from django.core.mail import...

3 minutes read.

Django Celery

Django is a python-based web framework. It is an open-source and free-to-use framework. Django uses the Model View Template architecture. Django provides many functionalities to web developers. One of these...

3 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

Django Messages

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

6 minutes read.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 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 Create App

Django is a Python-based web framework that is based on the Model View Template architecture. In this post, we will go through the installation and setup for our first Django...

4 minutes read.

Django Template System

Django Template System Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model...

5 minutes read.

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 minutes read.

Django Forms

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

3 minutes read.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.