[英]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.