1

I'm trying to retrieve a token for the user using the following request through Postman.

http://127.0.0.1:8000/api-token-auth/ JSON Body -

{
    "username": "user1",
    "password": "testpass"
}

The following is the error response -

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

I've checked the instructions provided in the official DRF Authentication document as well as various other question posts and implemented the following code.

settings.py

INSTALLED_APPS = [
    ...

    'rest_framework',
    'rest_framework.authtoken',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    'rest_auth',
    'rest_auth.registration',

    ....
]

AUTH_USER_MODEL = 'users.CustomUser'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

signals.py

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

urls.py

from django.contrib import admin
from django.urls import include, path, re_path
from django_registration.backends.one_step.views import RegistrationView
from rest_framework.authtoken import views as authtoken_views

urlpatterns= [
 path('admin/', admin.site.urls),
 
    path("accounts/",
         include("django_registration.backends.one_step.urls")),

    path("accounts/",
         include("django.contrib.auth.urls")),

  path("api-auth/",
         include("rest_framework.urls")),

    path("api-token-auth/", authtoken_views.obtain_auth_token, name="api-token-auth"),

    path("api/rest-auth/",
         include("rest_auth.urls")),

    path("api/rest-auth/registration/",
         include("rest_auth.registration.urls")),
]

Have I missed something?

pa1245
  • 53
  • 7

1 Answers1

2

Found the issue. The issue was not with the implementation, rather it was with Postman. Postman interceptor had retrieved cookies from the browser and had stored the CSRF Token with it. This token was automatically added to the request headers and hence, django tried to authenticate this request from Session Authentication which naturally should fail.

The solution- Open the Postman cookies and Delete the CSRF Token.

PS- A curl request can always help in verifying such issues

pa1245
  • 53
  • 7
  • I just ran into this today, and was surprised when I chose to "show hidden headers" and... there were cookies I didn't set. – Andrew Dec 07 '20 at 21:58