Codementor Events

CSRF Token with Django web application

Published Aug 31, 2018Last updated Feb 27, 2019
CSRF Token with Django web application

What is CSRF?

We often get promotional emails for a product or services from the website we visited sometime in the past. The email content may have links behind some flashy images which will take us to a website we logged in previously. We may not be sure what parameters are encoded as a querystring in the hyperlink and what kind of data theft that the parameters could cause. This is generally being achieved by CSRF attack.

CSRF is known as Cross-site request forgery, which is quite a common threat in web application. This attack is forged primarily like malicious social engineering through email or advertisement links that might harm the website functionality adversely.

CSRF protection in Django web application

In web application, basically the webforms take input from user and send them to server side components to process them. The server side components generally expose the service as a POST, PUT, DELETE methods for accepting the data over HTTP. It is considered to be a good practice to generate unique CSRF_TOKEN and send it along with the HTTP request, thus business functionality behind the exposed service will be protected from such threat.

How to pretect CSRF in Django web application

By default Django framework provides way to configure CSRF token in the application. If the form does not have csrf_token then Django simply throws a HTTP error as 403,

Forbidden (403) CSRF verification failed. Request aborted.

Let us see how to midicate this problem by doing few simple configurations.

Step 1:

First thing is, we need to activate the django.middleware.csrf.CsrfViewMiddleware in the settings.py file.

MIDDLEWARE = [
    'django.middleware.csrf.CsrfViewMiddleware', # CSRF middleware is added in the list
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Step 2:

In the view we will have to add a context dictionary in RequestContext object and pass them through render_to_response() method.

def get(request):
  context = RequestContext(request)
    context_dict = {}
    # Key statement needs to be added
    return render_to_response("your_template.html", context_dict, context)

Step 3:

We need to add a csrf_token value as an element in the context dictionary object.

def get(request):
  context = RequestContext(request)
    context_dict = {}
  # Update the dictionary with csrf_token 
  conext_dict.update(csrf(request))
    return render_to_response("your_template.html", context_dict, context)

Step 4:

Use the csrf_token in the HTML template file as a hidden field value that will be sent along with the form post request.

<input type="hidden" id="csrf_token" value='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>

Conclusion

Django is a very friendly framework for python developers, at the same time we need to know where to configure for what, otherwise we will be spinning in a endless timeloop. Hope the about post is informative to you. Thanks.

Discover and read more posts from Venkataramanan
get started
post commentsBe the first to share your opinion
Vidya R V
4 years ago

Hi, Can u give the complete code for step 4 ? I am really new to web development and django. If u can give the full html line for defining csrf_token as a hidden field , that would be helpful.

Show more replies