python - DRF 令牌身份验证 - 无法在 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 拦截器已从浏览器中检索到 cookie,并与它一起存储了 CSRF 令牌。该令牌被自动添加到请求标头中,因此,django 尝试从会话身份验证中对该请求进行身份验证,这自然会失败。
解决方案 - 打开 Postman cookie 并删除 CSRF 令牌。
PS- curl 请求始终可以帮助验证此类问题
推荐阅读
- html - 带有 colspan 的 HTML 表格显示错误
- angular - Highstocks 将范围选择器更改为下拉菜单
- spring-cloud-contract - Spring Cloud Contract for provider - 设置可选标头
- image - 如何在树枝模板中显示图像 GD 资源
- linker - 手动编译OpenSSL:制作共享对象时不能使用符号;使用 -fPIC 重新编译
- ocr - 为什么 Microsoft Cognitive 不返回每个 OCR 字段?
- angular - 在环境上下文中不允许使用 Angular2 打字稿错误初始化程序
- swift - 在单独文件中定义的 Swift 结构是否需要初始化程序?
- autodesk-forge - 下载衍生文件时的 HTTP 状态码
- docker - docker-compose.yml 中指定的资源限制没有被 docker 考虑