[英]DRF Token Authentication - not able to retrieve Token on Postman
我正在嘗試通過 Postman 使用以下請求為用戶檢索令牌。
http://127.0.0.1:8000/api-token-auth/ JSON 主體-
{
"username": "user1",
"password": "testpass"
}
以下是錯誤響應 -
{
"detail": "CSRF Failed: CSRF token missing or incorrect."
}
我檢查了官方 DRF 身份驗證文檔中提供的說明以及各種其他問題帖子,並實現了以下代碼。
設置.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',
)
}
信號.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)
網址.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")),
]
我錯過了什么嗎?
發現了問題。 問題不在於實現,而在於 Postman。 Postman 攔截器從瀏覽器中檢索到 cookies 並存儲了 CSRF 令牌。 此令牌自動添加到請求標頭中,因此 django 嘗試從 Session Authentication 驗證此請求,這自然會失敗。
解決方案 - 打開 Postman cookies 並刪除 CSRF 令牌。
PS- A curl 請求始終可以幫助驗證此類問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.