简体   繁体   中英

Apply tokenauthentication Django rest framework on part of the API view based on the type of the request

I am new to Django rest framework and struggling with api view token authentication. Following is my code

@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
            )

I need to apply tokenauthentication on part of the view not on whole view. Authentication should be based over type of the request. For example If type is POST there should not be any authentication but for the same view if request came in as PUT, GET, PATCH etc it should authenticate request.

If I understand well you want to apply IsAuthenticated permission to your view except when the the method is a POST .

I would suggest to create a Custom Permission :

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

And use that class instead of IsAuthenticated in your @permission_classes decorator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM