【问题标题】:DRF django-rest-framework-simplejwt JWTAuthentication not workingDRF django-rest-framework-simplejwt JWTAuthentication 不起作用
【发布时间】:2020-11-17 14:59:45
【问题描述】:

理想情况下使用django-rest-framework-simplejwt 和身份验证类JWTAuthentication,当我错误地传递令牌时,API 应该提供403

相反,当我发出 API 请求时,即使没有身份验证令牌,它也会成功执行。

这是一个虚拟 API,我关心的是身份验证应该起作用。

我的代码如下所示:

class ViewSet(viewsets.ModelViewSet):
    queryset = get_user_model().objects.all()
    serializer_class = SomeSerializer
    http_method_names = ("post", "patch")
    authentication_classes = (JWTAuthentication,)

当我调试时,我看到它正在执行 JWTAuthentication,它又返回 None。 这是预期的,因为我没有在标头中传递令牌。

    def authenticate(self, request):
        header = self.get_header(request)
        if header is None:
            return None

现在我认为 View 应该给予 Permission Denied,这并没有发生。

无法理解这里缺少什么。

【问题讨论】:

    标签: django django-rest-framework django-rest-framework-simplejwt


    【解决方案1】:

    如果您传递了错误的令牌,它将传递 401 状态响应。
    但是如果你没有在你的请求中加入授权头,django 将不会返回 401 响应,并且会像 AnonymousUser 请求一样处理请求。 如果您希望只有经过身份验证的用户可以访问您的 ViewSet,则应将 permission_classes = [IsAuthenticated,] 放入您的 ViewSet

    IsAuthenticated权限类可以从 rest_framework.permissions

    导入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-12
      • 2021-06-23
      • 2020-05-24
      • 2020-02-06
      • 2017-07-24
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      相关资源
      最近更新 更多