Django 需要 CSRF 令牌POST
默认请求。以避免 CSRF 令牌。
不要使用SessionAuthentication
作为身份验证类,因为它会强制您添加 CSRF 令牌。
如果您还想使用SessionAuthentication
然后你可以使用它覆盖
def enforce_csrf(self, request):
method
尝试下面这个:
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
pass
并在您的视图中使用它:
authentication_classes = (CsrfExemptSessionAuthentication ,TokenAuthentication)
如果您想在全局范围内使用它,可以将其放置在 REST_FRAMEWORK settings.py 文件中,如下所示:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'myapp.path-to-file.CsrfExemptSessionAuthentication'
],
}
请确保在 REST_FRAMEWORK 设置中添加正确的文件路径
使用令牌进行身份验证。
您必须这样请求:
curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
另请确保您已将其添加到 INSTALLED_APP 中:
INSTALLED_APPS = [
''''
'rest_framework',
'rest_framework.authtoken',
]
更多详情可在这找到:https://www.django-rest-framework.org/api-guide/authentication/ https://www.django-rest-framework.org/api-guide/authentication/