Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exempt CSRF Protection on direct_to_template

Tags:

django

csrf

I have a flow in my django application in which I redirect the user to another service (e.g. PayPal) which after some its own processing, returns the user back on my own server. The returning point on my server is a simple HTML success page which I render using direct_to_template.

For some odd reasons, the other server sends a POST request and hence the user sees a CSRF token missing error as the other server doesn't send back any CSRF token.

How do I exempt a direct_to_template view from CSRF tokens?

like image 567
sharjeel Avatar asked Jul 23 '12 10:07

sharjeel


People also ask

How can I be exempt from CSRF?

You can use the csrf_exempt decorator to disable CSRF protection for a particular view.

What is the use of CSRF exempt in Django?

Normally when you make a request via a form you want the form being submitted to your view to originate from your website and not come from some other domain. To ensure that this happens, you can put a csrf token in your form for your view to recognize.

How does Django prevent CSRF?

Django protects against CSRF attacks by generating a CSRF token in the server, send it to the client side, and mandating the client to send the token back in the request header. The server will then verify if the token from client is the same as the one generated previously; if not it will not authorise the request.

What is CSRF token in Django?

The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.


1 Answers

You can use the csrf_exempt decorator to disable CSRF protection for a particular view.

Say your url pattern is:

('^my_page/$', direct_to_template, {'template': 'my_page.html'}) 

Add the following import to your urls.py:

from django.views.decorators.csrf import csrf_exempt 

Then change the url pattern to:

('^my_page/$', csrf_exempt(direct_to_template), {'template': 'my_page.html'}) 
like image 129
Alasdair Avatar answered Oct 22 '22 02:10

Alasdair