CSRF Failed: CSRF token missing or incorrect

前端 未结 12 727
臣服心动
臣服心动 2020-11-29 02:42

I\'m using Django 1.7 and django-rest-framework.

I made an API that returns me some JSON data putting this in my settings.py

REST_FRAMEW         


        
相关标签:
12条回答
  • 2020-11-29 03:07

    When you are using SessionAuthentication, you are using Django's authentication which usually requires CSRF to be checked. Django REST Framework enforces this, only for SessionAuthentication, so you must pass the CSRF token in the X-CSRFToken header.

    The Django documentation provides more information on retrieving the CSRF token using jQuery and sending it in requests. The CSRF token is saved as a cookie called csrftoken that you can retrieve from a HTTP response, which varies depending on the language that is being used.

    If you cannot retrieve the CSRF cookie, this is usually a sign that you should not be using SessionAuthentication. I recommend looking into TokenAuthentication or OAuth 2.0 depending on your needs.

    0 讨论(0)
  • 2020-11-29 03:09

    I had similar problem, I've wrapped my URLs under csrf_exempt method as -

    from django.views.decorators.csrf import csrf_exempt
    
    url(r'^api/v1/some-resource$', csrf_exempt(SomeApiView.as_view())),
    
    0 讨论(0)
  • 2020-11-29 03:13

    We had this problem and it turned out to be Postman's fault. They were automatically sending csrftoken and sessionid default values which we weren't passing in the header. Following this tutorial helped fix the issue: https://avilpage.com/2019/02/django-tips-csrf-token-postman-curl.html

    0 讨论(0)
  • 2020-11-29 03:13

    django1.8 python2.7

    {
        "detail": "CSRF Failed: CSRF token missing or incorrect."
    }
    

    I fix it by using other httpmethod; oh, I face it again, this time is because I paste it, there are some invisible characters

    0 讨论(0)
  • 2020-11-29 03:18

    1- Search for the Cookie header

    2- Separate the csrftoken from the sessionid

    3- Add the X-CSRFToken={..the csrftoken that you extracted in step 2..} see below

    4- Post again

    0 讨论(0)
  • 2020-11-29 03:19

    When you host django website on Apache server. Djando rest framework with TokenAuthentication and SessionAuthentication will get

    CSRF Failed: CSRF token missing or incorrect

    To fix this open Apache configuration file - httpd.conf Add following line:

    WSGIPassAuthorization On
    
    0 讨论(0)
提交回复
热议问题