我已经使用 Django Rest Framework 创建了 REST API,并将 django-rest-auth 用于身份验证端点。这些 API 用于移动应用程序。我已经使用 TokenAuthentication 来保护 API。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
使用 APIDOC 时会出现问题。我已经使用 coreapi 添加了 apidoc。文档也需要受到保护。当我使用上述设置访问 /docs/ 时出现以下错误:
'dict' object has no attribute 'data'
所以我启用了 SessionAuthentication。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
这导致登录端点 (/rest-auth/login) 因 CSRF 错误而中断。
{
"detail": "CSRF Failed: CSRF token missing or incorrect."
}
那么如何分别使用 TokenAuth 和文档保护端点?或者我可以完全绕过登录端点的安全性吗?
可以在定义 URL 时单独定义身份验证类:
url(r'^docs/', include_docs_urls(title='PeySO API Doc', public=False,
authentication_classes=[SessionAuthentication])),
这允许我们只为文档启用 SessionAuthentication,并为 API 端点使用 TokenAuthentication。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句