Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using different authentication for different operations in ModelViewSet in Django REST framework

I have the following ModelViewSet

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated, MyUserPermissions)

I want the create method (POST on /users/) to not ask for any authentication. How can I override the authentication_classes in this case? I'm talking about ModelViewSet not generic API views.

like image 234
dado_eyad Avatar asked Feb 14 '23 14:02

dado_eyad


1 Answers

I want the create method (POST on /users/) to not ask for any authentication.

Actually that's not quite what you want. You want POST on users to not require any permissions, which will have the effect that either authenticated or unauthenticated requests will succeed.

I'd suggest overriding your permission classes so that they always allow POST requests. Follow the custom permissions documentation for more info on that.

Essentially you'll have something like:

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

And probably something similar for your other permission class too.

like image 161
Tom Christie Avatar answered Feb 16 '23 10:02

Tom Christie