Search code examples
curldjango-rest-frameworktoken

Redirect to Login Page after Request with Token Authentication


I have a django application where we had basic django views and templates for our UI. Now we want to replace the frontend with react. For authentication, we are using TokenAuthentication. So, if I understand it correctly, it should work like this:

  1. POST username and password to your API to get a Token.
  2. make a request to you API and add your Token to the header like Authorization: Token 31271c25207ef084ca6e1c0af65a08d0c8f0897a

To get the Token, I added this to my urls.py:

path(r"api/v1/api-token-auth/", views.obtain_auth_token, name="api_token_auth"),

which returns a token after posting username and password like this:

curl -X POST "http://0.0.0.0:8001/api/v1/api-token-auth/" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{  \"username\": \"user-name\",  \"password\": \"S3cure-P4ssw0rd\"}"

this returns:

{"token":"31271c25207ef084ca6e1c0af65a08d0c8f0897a"}

this works fine.

now I want to GET something from my REST-API, but when I try it like:

curl -X GET "http://0.0.0.0:8001/api/v1/test/" -H  "accept: application/json" -H  "Authorization: Token 31271c25207ef084ca6e1c0af65a08d0c8f0897a"

it gives a 302 and redirects to /accounts/login/?next=/api/v1/test/ and I don't know why.


here's some code:

urls.py:

urlpatterns = [
    path(r"api/v1/api-token-auth/", views.obtain_auth_token, name="api_token_auth"),
    path(r"accounts/login/", auth_views.LoginView.as_view()),
    path(r"api/v1/test/", test.index_api, name="index_api"),
    ...
    path("logout/", LogoutView.as_view(), name="logout"),
]

settings.py:

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
    "TEST_REQUEST_DEFAULT_FORMAT": "json",
}
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "rest_framework.authtoken",
    ...
]

if more information are needed, please let me know.

thank you!


Solution

  • ok, I figured it out.

    I had the decorators @login_requiredand @staff_member_required in the view which are from django and not from rest_framework. I had to use rest_frameworks permission classes instead of Django's decorators.

    explanation and more details from this post: Token authentication in django (rest_framework) not working