{ "detail": "CSRF 失败:CSRF 令牌丢失或不正确。" }

时间:2021-07-24 05:56:11

标签: django django-rest-framework postman django-csrf csrf-token

enter image description here

大家好。我尝试使用 DRF 和 Postman 在我的应用程序中注册一个新产品。 当我发送请求时,我收到此错误。 问题只是关于我的 csrf_token。 如果你帮助我,我将不胜感激......

这是我的看法

class ProductViewSet(viewsets.ModelViewSet):
    authentication_classes = (SessionAuthentication,TokenAuthentication) 
    permission_classes = [IsAdminUser]
    queryset = ProductInfo.objects.all().order_by('-id')
    serializer_class = ProductSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ['title','code','owner__username']

我对 GET 请求没有任何问题。

2 个答案:

答案 0 :(得分:0)

Django 默认在 POST 请求中需要 CSRF 令牌。避免 CSRF 令牌。

不要使用 SessionAuthentication 作为身份验证类,因为它会强制您添加 CSRF 令牌。

如果您仍然想使用 SessionAuthentication 那么您可以使用它覆盖

def enforce_csrf(self, request): 方法

试试下面这个:

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/

答案 1 :(得分:0)

因为 csrf_token 方法不需要 GET

您可以像这样在标题中设置 csrf_token

X-CSRFToken: your_csrf_value  

因此,不要使用 Cookie,而是将 X-CSRFToken 添加到 POSTMAN 中的标头。