iMerica / dj-rest-auth

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

"CSRF failed: CSRF token missing." when trying to log in #474

Closed brylie closed 1 year ago

brylie commented 1 year ago

In a hybrid site with an HTML UI and REST client, it is common to have CSRF enabled to protect website visitors from malicious activity.

https://stackoverflow.com/a/26639895/1191545

However, when enabling dj-rest-auth and trying to make POST requests to endpoints, such as login/, Django is producing CSRF errors:

403 FORBIDDEN "detail": "CSRF Failed: CSRF token missing."

https://stackoverflow.com/questions/26639169/csrf-failed-csrf-token-missing-or-incorrect

It may be necessary to wrap the dj-rest-auth URLs in a csrf_exempt decorator, as per this comment:

https://stackoverflow.com/a/48879567/1191545

brylie commented 1 year ago

The solution for me in this case was to remove the following line from REST_FRAMEWORK config

"rest_framework.authentication.SessionAuthentication",

So my REST_FRAMEWORK config looks like this:

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.TokenAuthentication",
    ),
    "DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema",
}