iMerica / dj-rest-auth

Authentication for Django Rest Framework
https://dj-rest-auth.readthedocs.io/en/latest/index.html
MIT License
1.69k stars 319 forks source link

CSRF Failed: CSRF cookie not set when setting REST_SESSION_LOGIN = False and using JWT_AUTH_COOKIE. #334

Closed Aakarshit-Sharma19 closed 3 years ago

Aakarshit-Sharma19 commented 3 years ago

Hey @iMerica, So, when I am logging in using LoginView provided by the library and not using session login in dj rest auth, the csrf cookie is not being set. The config is as follows,

REST_USE_JWT = True
REST_SESSION_LOGIN = False
JWT_AUTH_COOKIE = 'auth' 
JWT_AUTH_REFRESH_COOKIE = 'refresh'
JWT_AUTH_COOKIE_USE_CSRF = True
SIMPLE_JWT = {
    'ROTATE_REFRESH_TOKENS': True
}

Is this a bug in the library?

iMerica commented 3 years ago

We have tests that assert this feature is working.

https://github.com/iMerica/dj-rest-auth/blob/master/dj_rest_auth/tests/test_api.py#L819

Can you list the steps to reproduce?

Aakarshit-Sharma19 commented 3 years ago

For my project, I am using latest packages for django, dj-rest-auth,simplejwt and so on. The configuration in settings.py is as follows,


REST_USE_JWT = True
REST_SESSION_LOGIN = False
JWT_AUTH_COOKIE = 'auth'  # The cookie key name can be the one you want
JWT_AUTH_REFRESH_COOKIE = 'refresh'
JWT_AUTH_COOKIE_USE_CSRF = True
SIMPLE_JWT = {
    'ROTATE_REFRESH_TOKENS': True
}

ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = "none"

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    )
}

The urls.py for accounts app is as follows,

from django.urls import path, include
from accounts import views
# from rest_framework_simplejwt.views import token_refresh_sliding
from dj_rest_auth.views import LoginView
from dj_rest_auth.jwt_auth import get_refresh_view
urlpatterns = [
    path('login/', view=LoginView.as_view(), name='accounts-token'),
    path('token/', include([
        path('refresh/', view=get_refresh_view().as_view(),
         name='accounts-token-refresh')
    ]))
]

When using postman to send credentials to the login api with dummy credentials such as,

{
    "email": "admin@example.com",
    "password": "admin"
}

only two cookies are being set 'auth' and 'refresh' and csrftoken is only being set when REST_SESSION_LOGIN=True but accompanied by the unnecessary 'sessionid'.

indraneelpatil commented 10 months ago

@Aakarshit-Sharma19 How did you resolve this? I get the same CSRF failed error while trying to use postman

Aakarshit-Sharma19 commented 10 months ago

@indraneelpatil Please refer to this issue for the solution: https://github.com/iMerica/dj-rest-auth/issues/338