Django check CSRF token manually

后端 未结 4 1015
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 02:27

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 app

4条回答
  •  旧巷少年郎
    2021-02-08 03:04

    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.

提交回复
热议问题