Using django with postman {"detail":"CSRF Failed: CSRF token missing or incorrect."}
Asked Answered
G

9

16

I'm using postman to check json response from my django-rest-framework.

When my first try to post id, email, password through POST method to my django on AWS(amazon web services), it works well. It returned like:

  {
    "key": "99def123123123123d88e15771e3a8b43e71f"
}

But after first try, the other words, from second try it returned

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

(Additionally edit +) My putty terminal says "POST /rest-auth/login/ HTTP/1.1" 403 58

I saw http://kechengpuzi.com/q/s31108075, but it is not proper to my case.

and from http://django-rest-framework.narkive.com/sCyJk3hM/authentication-ordering-token-vs-session, i can't find solution which is using postman

  1. How can i use postman appropriately?

  2. Or Could you recommend other tools to use?

I'm making android application with retrofit2 So I need tools to check POST, GET method and responses.

Gilley answered 4/9, 2016 at 9:24 Comment(5)
Did you mean you get different results between two request without change anything?Dip
Yes, i post { "username": "thesamething", "email": "thesamething", "password": "thesamething" } using POST method in first try and other tries. When i use POST method on same way at given DRF html page that i copied from DRF(actually django-rest-auth), this error has not happened. But on postman, it's happened.Gilley
Did you set carf token in your request?Dip
I put Headers key : e0af91707f0434a1a2a7581dd3f4f48d3bdad717 or Authorization : e0af91707f0434a1a2a7581dd3f4f48d3bdad717 or Authorization : "key": "99def123123123123d88e15771e3a8b43e71f" but it doesn't work. As you said, I think i'm wrong with using header. What is correct way putting authorization key? Where can i check it?Gilley
Try setting the X-CSRFToken header in Postman with the received CSRF token (see #26639669)Scammony
D
9

Your api need CSRF token, you have to add CSRF token to the request(and postman):

data: { csrfmiddlewaretoken: csrf_token, "username": "thesamething", "email": "thesamething", "password": "thesamething" }

You can get CSRF token from your form input field(you will find a hidden field if you use django build-in form api) or if you use Ajax, you can have a look at Cross Site Request Forgery protection.It has nothing to do with your authorization key, your key is use to identify who you are, and CSRF token is to make sure this request is send from your server.

Dip answered 4/9, 2016 at 14:32 Comment(2)
Do i have to add data: { csrfmiddlewaretoken: csrf_token, "username": "thesamething", "email": "thesamething", "password": "thesamething" } in postman's Body? Do not change anything in Headers?Gilley
Try setting the X-CSRFToken header in Postman with the received CSRF token (see https://mcmap.net/q/195387/-csrf-failed-csrf-token-missing-or-incorrect)Scammony
L
26

If using token based authentication with DRF don't forget to set it in settings.py. Otherwise you'll get a CSRF error

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}
Larue answered 15/9, 2018 at 18:28 Comment(0)
C
14

I was facing the same problem with Postman. I was asked to include a CSRF on every request after getting a token for the first time so I realized that I had Session and Token authentication methods enabled so I commented out the SessionAuthentication line (of course, you could remove it as well)

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

After that, I was able to request a token by using only my credentials without including any CSRF code:

Successful token requests

I think that the fact of having those two auth classes activated was causing Django to muddle up somehow.

Compliment answered 12/5, 2019 at 17:19 Comment(1)
THANK YOU. Probably an edge case but I ran into this issue still I was stripping out JWT token auth from an app and couldn't figure out the problem.Brainbrainard
D
9

Your api need CSRF token, you have to add CSRF token to the request(and postman):

data: { csrfmiddlewaretoken: csrf_token, "username": "thesamething", "email": "thesamething", "password": "thesamething" }

You can get CSRF token from your form input field(you will find a hidden field if you use django build-in form api) or if you use Ajax, you can have a look at Cross Site Request Forgery protection.It has nothing to do with your authorization key, your key is use to identify who you are, and CSRF token is to make sure this request is send from your server.

Dip answered 4/9, 2016 at 14:32 Comment(2)
Do i have to add data: { csrfmiddlewaretoken: csrf_token, "username": "thesamething", "email": "thesamething", "password": "thesamething" } in postman's Body? Do not change anything in Headers?Gilley
Try setting the X-CSRFToken header in Postman with the received CSRF token (see https://mcmap.net/q/195387/-csrf-failed-csrf-token-missing-or-incorrect)Scammony
S
7

For me the solution was to add the X-CSRFToken header in Postman (gotten from initial login response in browser)

see https://mcmap.net/q/195387/-csrf-failed-csrf-token-missing-or-incorrect

Scammony answered 5/8, 2020 at 10:6 Comment(0)
P
1

In settings.py file

INSTALLED_APPS = [
...
...
...
...
'rest_framework.authtoken',
...
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
}

in project urls.py

from rest_framework.authtoken import views

urlpatterns = [
    ....
    path('api-token-auth/',views.obtain_auth_token,name='api-token-auth')

]

Open terminal as

$ pip3 install httpie
$ python3 manage.py createsuperuser # if not created
$ http POST http://localhost:8000/api-token-auth/ username="username" password = "password"   # You will get token key (Just copy it) ex:a243re43fdeg7r4rfgedwe89320

You token key will be also automatically saved in your databases

Go to postman header (like in example) Ex: screenshot from postman ,where and how to paste accessed toke Then insert you token key.

reference to get token key from this video

Puke answered 13/2, 2021 at 8:36 Comment(0)
J
0

You can either use csrfmiddlewaretoken: csrf_token, in your json data where csrf_token is a valid token, but in a situation where including it you are unable to provide a correct token, comment or remove SessionAuthentication as below.

'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework.authentication.TokenAuthentication',
    # 'rest_framework.authentication.SessionAuthentication',
]
Jerrine answered 27/4, 2020 at 18:37 Comment(0)
R
0
  • Create an endpoint which return html page. Endpoint - /get_token Details - The html page will have only 1 line of code i.e. {{ csrf_token}}. Request that url from postman. In response you will see the token

  • For new post method endpoint, add the header with name X-CSRFToken and value as csrf_token. Send the json data according to requirement. enter image description here enter image description here

Ruvolo answered 27/9, 2023 at 13:58 Comment(0)
R
0

I solved this problem like this:

from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse

@csrf_exempt def your_view(request):
    if request.method == 'POST':
        # Handle your POST request here
        return JsonResponse({'message': 'POST request received'})
    else:
        return JsonResponse({'error': 'Only POST requests are allowed'})
Ruthi answered 19/6 at 12:13 Comment(0)
H
-1

i changed request method from post to patch and i could login

Hike answered 7/12, 2019 at 12:19 Comment(1)
Making a patch is not a solution,I would not recommend making it as patch/put eitherNomology

© 2022 - 2024 — McMap. All rights reserved.