Mehdi bahmanpour
Mehdi bahmanpour

Reputation: 614

Django rest_framework, disable authentication and permission in specific method

I have a class called UserViewSet :

class UserViewSet(viewsets.ModelViewSet):
    queryset = UserData.objects.all()
    serializer_class = UserSerializer
    from rest_framework.permissions import IsAuthenticated
    from rest_framework.authentication import TokenAuthentication
    permission_classes = (IsAuthenticated,)
    authentication_classes = (TokenAuthentication,)

    @action(methods=['post'], detail=False)
    def signup_user(self, request):
        request_data = request.query_params
        if len(request_data) == 0:
            return Response("Empty params !")

Now i want to signup a new user and it will raise this error :

{ "detail": "Authentication credentials were not provided." }

Its because of Authentication and Permission classes .

So whats the correct way to disable this classes in signup function ?

I used authentication_classes and permission_classes decorators but it has no effect on this function.

Upvotes: 3

Views: 1634

Answers (2)

Gathiira M.
Gathiira M.

Reputation: 144

and for the default actions, i.e create , retrieve , update , partial_update , destroy and list, you can override the get_permissions method (for subclasses of rest mixins only) i.e

def get_permissions(self):
    permission_classes = []
    if self.action =='create':
        permission_classes = [AllowAny,]
    else:
        permission_classes = [IsAuthenticated,]

    return [permission() for permission in permission_classes]

at this point, you can even validate with the http methods, ie POST, GET, PUT ... by referencing self.request.

The same can be done to authentication_classes by overriding get_authenticators method

def get_authenticators(self):
    """
    Instantiates and returns the list of authenticators that this view can use.
    """
    authentication_classes = []
    if self.action !='create':
        authentication_classes = [TokenAuthentication, ]
    
    return [auth() for auth in authentication_classes]

Upvotes: 1

spectras
spectras

Reputation: 13552

The action decorator allows specifying action-specific permission classes. This should do:

    @action(methods=['post'], detail=False, permission_classes=[AllowAny])
    def signup_user(self, request):
        # ...

(don't forget importing AllowAny)

Upvotes: 3

Related Questions