I am trying to figure out how to authenticate to the Django REST Framework with Postman. I have a Postman interceptor. But no matter what I try, I seem to get a 403 - CSRF verification failed. Request aborted.
In chrome, I go to DRF's default login point. I enter the username and password and click submit. It works in Chrome. With interceptor, I can see the POST. Now if I try that exact same POST in Postman, I get a 403 with the CSRF error. How is that even possible? Postman is doing exactly the same thing that chrome is doing. How can it be producing a different result?
Here's me logging in from Chrome...
Here's me doing the * exact same thing* with postman...
What am I missing? I keep reading about doing a GET request, looking at the set-cookie csrf token and value, and putting that in a header on my POST request. I've tried that and every variation I can think of to no avail.
Postman is an excellent tool for developing and testing APIs, and we will only scratch the surface of its features in this article. To start, navigate to the taskmanager directory that contains manage.py and run the command python manage.py migrate to apply the database migrations to Django's default sqlite database.
JSON Web Token (JWT) Authentication This is a new and popular standard that works similar to TokenAuthentication except that it does not need to save tokens in the database.
For Basic Authentication Authorization, we have to choose the option Basic Auth from the TYPE dropdown, so that the Username and Password fields get displayed. First we shall send a GET request for an endpoint (https://postman-echo.com/basic-auth) with the option No Auth selected from the TYPE dropdown.
from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...
Initially, send an HTTP GET request to the /api/auth/login/
URL (the login page) using Postman. This step is important to get the csrftoken
from the response.
Before HTTP GET request
After sending the HTTP GET request, you will receive a csrftoken
cookie as below,
Use this value in next HTTP POST request by settings it in the request header.
Alternatively, you can send the csrf token along with form-data instead of the header, using csrfmiddlewaretoken
key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With