【问题标题】:{ "detail": "CSRF Failed: CSRF token missing or incorrect." }{ "detail": "CSRF 失败:CSRF 令牌丢失或不正确。" }
【发布时间】:2021-10-01 01:35:27
【问题描述】:

大家好。我尝试使用 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 请求没有任何问题。

【问题讨论】:

  • GET 正在工作,因为它不需要 csrf。您是否需要此视图的会话身份验证?如果是,您是如何获得 csrf 令牌的?
  • 是的,如果我不使用它,我无法发送获取请求。
  • 我应该在邮递员标题中添加什么?
  • 你从哪里得到 csrf 令牌?
  • 在邮递员标头(Cookie)标头中我明白了

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


【解决方案1】:

默认情况下,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/

【讨论】:

  • 当我不使用它时,我得到一个{"detail":"Authentication credentials were not provided."}
  • 因为你还没有添加令牌
  • 我现在不知道该怎么办
  • 我已经添加了授权和不记名令牌
  • 等等,我正在更深入地更新答案
【解决方案2】:

因为GET 方法不需要csrf_token

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

X-CSRFToken: your_csrf_value  

所以不要使用Cookie,而是将X-CSRFToken 添加到POSTMAN 的标题中。

【讨论】:

    猜你喜欢
    • 2014-02-26
    • 2014-12-25
    • 1970-01-01
    • 2021-06-04
    • 2020-09-19
    • 2021-07-14
    • 2012-05-16
    • 2016-12-31
    • 2017-01-11
    相关资源
    最近更新 更多