【问题标题】:Apply tokenauthentication Django rest framework on part of the API view based on the type of the request根据请求的类型在部分 API 视图上应用 tokenauthentication Django rest framework
【发布时间】:2017-11-22 18:28:07
【问题描述】:

我是 Django REST 框架的新手,正在努力解决 api 视图令牌身份验证问题。 以下是我的代码

@api_view(['POST'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))

    def create_user(request):
        """
        API to add user
        """
        if request.method == 'POST':
            request_body = request.data['users']
            created_user_ids = []
            # Data must be provided and validated
            validation = UserSerializer(data=request_body, many=True)
            validation.is_valid(raise_exception=True)
            created_user_ids.append(validation.save())

            return Response(
                data={'users': [{'id': user_id} for user_id in created_user_ids]},
                content_type='json',
                status=status.HTTP_201_CREATED
            )

我需要在部分视图而不是整个视图上应用令牌身份验证。 身份验证应基于请求的类型。 例如 如果类型是 POST,则不应进行任何身份验证,但对于相同的视图,如果请求以 PUT、GET、PATCH 等形式出现,则应该对请求进行身份验证。

【问题讨论】:

    标签: python django rest authentication django-rest-framework


    【解决方案1】:

    如果我理解得很好,您希望将IsAuthenticated 权限应用于您的视图,除非方法是POST

    我建议创建一个Custom Permission:

    class IsAuthenticatedOrPost(IsAuthenticated):
        def has_permission(self, request, view):
            if request.method == 'POST':
                return True
            return super().has_permission(request, view)
    

    并在您的 @permission_classes 装饰器中使用该类而不是 IsAuthenticated

    【讨论】:

      猜你喜欢
      • 2017-04-27
      • 2013-07-07
      • 2016-11-13
      • 2016-11-04
      • 1970-01-01
      • 2018-06-26
      • 2019-01-07
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多