jdotjdot
jdotjdot

Reputation: 17052

Django Rest Framework Permissions Conflict

I'm having a bit of trouble with understanding the flow of Django Rest Framework authentication and permission. My REST_FRAMEWORK dict in settings.py is as follows:

# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],

'DEFAULT_AUTHENTICATION_CLASSES': (
#     # 'rest_framework.authentication.BasicAuthentication',
#     # 'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.TokenAuthentication',
),

I now am trying to make it so that only authenticated users can make the users-list or users-detail calls, but I do need unauthenticated users to be able to make calls to users-create. I have tried the following using rest_condition:

from rest_condition import Or, And, Not
class UserViewSet(ListOnlyIfAdminMixin, viewsets.ModelViewSet):
    queryset = U.objects.all()
    serializer_class = UserSerializer
    # Would this permission_classes declaration come before or be overridden by
    #   the decorator below?
    # permission_classes = [IsAuthenticated, IsAdminOrTargetUser,]

    @permission_classes([Or(Not(IsAuthenticated), IsAdminUser)])
    def create(self, request, *args, **kwargs):
         # stuff

But when I try to make a POST request to /api/users with the right information to create a new user, I get back the following:

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

Now, obviously authentication credentials couldn't be provided, because the user doesn't have an account or token yet. What's the way to enable a user to sign up without already requiring credentials?

Upvotes: 2

Views: 2697

Answers (1)

AdelaN
AdelaN

Reputation: 3536

From here you can see the order of setting a permission for a certain method.

So you can see that you are on the right path with setting the permissions only for the create function. However, I don't see why you need to do a rest_condition for your permission: a simple Not(IsAuthenticated), to override the default settings, would suffice.

Upvotes: 1

Related Questions