CSRF Failed: CSRF token missing or incorrect

120,446

Solution 1

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.

Solution 2

This is what i did to solve it, i included csrf token to the form and using jquery/ javascrip got the csrf token like this when document loaded

var $crf_token = $('[name="csrfmiddlewaretoken"]').attr('value');

the included it on jquery headers as follow

 $.ajax({
            type: "POST",
            url: "/api/endpoint/",
            data: newEndpoint,
            headers:{"X-CSRFToken": $crf_token},
            success: function (newEnd) {
                console.log(newEnd);
                add_end(newEnd);
            },
            error: function () {
                alert("There was an error")
            }
        });

Solution 3

I think it is a cookie issue.

Permanent Solution: If you are using Postman, First, clear the existing cookies by clicking 'X' s. Then add correct cookie.

Temporary Solution (for debugging): Try this in your settings.py:

'DEFAULT_AUTHENTICATION_CLASSES': [
    # 'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
]

Solution 4

1- Search for the Cookie header

enter image description here

2- Separate the csrftoken from the sessionid

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

enter image description here 4- Post again

Solution 5

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

Share:
120,446

Related videos on Youtube

Alex Lord Mordor
Author by

Alex Lord Mordor

Updated on July 05, 2022

Comments

  • Alex Lord Mordor
    Alex Lord Mordor 4 months

    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_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
        'DEFAULT_RENDERER_CLASSES': (
        #   'rest_framework.renderers.XMLRenderer',
        'rest_framework.renderers.JSONRenderer',
        #   'rest_framework.renderers.BrowsableAPIRenderer',
        )
    }
    

    When I make GET calls, it returns me all the data, but when I try with PUT/PATCH I get:

    --------Response Headers---------
    Status Code: 403
    Date: Wed, 29 Oct 2014 18:51:42 GMT
    Vary: Cookie
    Server: WSGIServer/0.1 Python/2.7.8
    Allow: GET, POST, PUT, PATCH, HEAD, OPTIONS
    X-Frame-Options: SAMEORIGIN
    Content-Type: application/json
    ---------------------------------
    --------Response Body-----------
    {"detail": "CSRF Failed: CSRF token missing or incorrect."}
    ---------------------------------
    

    This only happens when I am logged in, if I am anonymous I can PUT/PATCH correctly.

    I have tried with @csrf_exempt and I got errors, I have included the rest_framework.permissions.AllowAny in the setting...

    I have no idea what's going on. Does anyone know what the issue is?

  • Alex Lord Mordor
    Alex Lord Mordor about 8 years
    I know I should give the CSRF Token when I am authenticated, but, actually I am using a .NET Windows Forms Application to communicate with this API, and it makes the GET call by HTTPRequest and HTTPResponse methods, I have no idea how could I get the CSRF Token in this situation, I am not using AJAX nor HTML Forms. EDIT The .NET app receives plain text in JSON format, and it return the same
  • Alex Lord Mordor
    Alex Lord Mordor over 7 years
    When you use SessionAuthentication, by default django requires two "keys" one of them could be found in the cookies when a logged-in user is active and the other is the csrf-token, if they do not match, then an error is raised, so, there is the documentation like @Kevin said to make it authenticate in the correct way.
  • Little Brain
    Little Brain over 3 years
    For me it was simply that I'd forgotten to add the trailing '/' to my URL. Like @kokociel said, the issue was nothing to do with CSRF and instead that the URL wasn't resolving to any of my endpoints.
  • Willie Cheng
    Willie Cheng almost 3 years
  • Joe Sadoski
    Joe Sadoski 12 months
    I just spent the last half hour trying to find the header key, X-CSRFToken. I tried literally everything else. Thank you!
  • ming
    ming 11 months
    clear cookies solved my problem

Related