重定向至"请求令牌身份验证后登录页面"诊断树



我有一个django应用程序,在那里我们有基本的django视图和UI模板。现在我们想用react取代前端。对于身份验证,我们使用TokenAuthentication。所以,如果我理解正确的话,它应该是这样工作的:

  1. POST用户名和密码到您的API以获取令牌
  2. 向您的API发出请求,并将您的Token添加到标题中,如Authorization: Token 31271c25207ef084ca6e1c0af65a08d0c8f0897a

为了获得代币,我将其添加到我的urls.py:中

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

它在发布用户名和密码后返回一个令牌,如下所示:

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"}"

返回:

{"token":"31271c25207ef084ca6e1c0af65a08d0c8f0897a"}

这很好用。

现在我想从我的REST-API中GET一些东西,但当我尝试时,就像:

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

它给出了一个CCD_ 7并重定向到CCD_。


这里有一些代码:

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",
...
]

如果需要更多信息,请告诉我。

谢谢!

好吧,我想明白了。

视图中的装饰器@login_required@staff_member_required来自django,而不是rest_framework。我不得不使用rest_frameworks权限类,而不是Django的decorator。

这篇文章的解释和更多细节:django中的令牌身份验证(rest_framework(不工作

最新更新