Thursday, July 29, 2021

django - POST request and CSRF tokens

lets first know the difference between http get and post. 

HTTP GET :

  • The GET method is the default submission method for a form.
  • The GET method sends the data in the form of URL parameters. Therefore, any data sent with the help of the GET method remains visible in the URL. Since the data is exposed in the URL, the GET method is not considered to send sensitive information such as passwords.
  • The GET method reveals the data in the URL bar; therefore, the length of the URL increases. The maximum length of a URL is 2048 characters, so only a limited amount of data can be sent using the GET method. The following error occurs when we try to send more than 2048 characters using GET :

POST :

  • Data sent by the POST method never gets visible in the URL box, and therefore it is more secure than the GET method, and sensitive information can be sent with the help of this method.
  • Since the data is not visible in the URL query, the length of the URL remains less than 2048 characters, and a large amount of data can be sent with the help of the POST method.
  • Data is sent to the server in the form of packages in a separate communication with the processing script.


Now, we will start our discussion on CSRF tokens.

WHAT ARE CSRF TOKENS?

  • CSRF stands for Cross-Site Request Forgery.
  • The server-side application generates and transmits a huge, random, and unpredictable number to the client to make sure that the request is coming from the original client and not from a malicious website.
  • CSRF tokens are used to protect the site against CSRF attacks.


Use POST:

In the template, here index.html file add the post method in the form.

<form action="/removePunctuation" method="post">

In the views.py, replace all the request.GET.get with the request.POST.get. 

from django.http import HttpResponse
from django.shortcuts import render


def removePunc(request):
# text=request.GET.get('text','default')
text = request.POST.get('text', 'default')
# text = request.POST.get('text', 'default')
check = request.POST.get('removepunc','off')

If you now test from server, you will get the CSRF error:

Test:

Error:

Use CSRF token:

To overcome the CSRF error, add the {% csrf_token%} in the template form

<form action="/removePunctuation" method="post">{% csrf_token %}


Test:

Success page:

1 comment:

Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...