Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django check CSRF token manually

I am implementing an API that works either with an API key, or with a CSRF token. The goal is for it to be usable either by a web app (protected by CSRF) or by a third party application (protected by API key).

Basically on each request (all via POST), I check if there is an API key. If there is a valid one, it's good to go. If not, I want to fall back to verifying CSRF.

Is there a function I can call to verify the CSRF myself? The view itself is @csrf_exempt because API keys need to work.

like image 448
Luke Sapan Avatar asked Apr 05 '15 05:04

Luke Sapan


People also ask

How does Django verify CSRF tokens?

You don't need to check on each request, as CSRF tokens should only really be used on POST and PUT requests. Second, you can't verify a CSRF token unless you are generating it on each request, and your verification is optional. A CSRF token is not the same as an API key.

Where is CSRF token stored 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.

How do I get CSRF token in Postman Django?

Instead, we can use Postman scripting feature to extract the token from the cookie and set it to an environment variable. In Test section of the postman, add these lines. var xsrfCookie = postman. getResponseCookie("csrftoken"); postman.

What is Csrf_exempt?

csrf_exempt (view) This decorator marks a view as being exempt from the protection ensured by the middleware. Example: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_view(request): return HttpResponse('Hello world')


1 Answers

In my case, I wanted to POST some raw data with CSRF check.

So, I use this decorator requires_csrf_token in the view which process POST data :

from django.views.decorators.csrf import requires_csrf_token

@requires_csrf_token
def manage_trade_allocation_update(request):

In my template, I added csrf_token génération and put it in data post :

{% csrf_token %}
...
data['csrfmiddlewaretoken'] = document.querySelector('input[name="csrfmiddlewaretoken"]').value;

With this mecanism, I can use CSRF protection with manual HTTP POST request.

like image 72
Samuel Dauzon Avatar answered Oct 22 '22 14:10

Samuel Dauzon