Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework won't let me have more than one permission

I have a problem with the Django Rest Framework and permissions. DRF won't let me have more than one permission on my views for example.

If I login to the API as an admin user I can get access using this mixin:

class PermissionMixin(object):
    permission_classes = (permissions.IsAdminUser)

Now, if I add a second permission mixin:

class PermissionMixin(object):
    permission_classes = (permissions.IsAdminUser, TokenHasReadWriteScope)

Admin users are denied access. What should happen is both admin user and users with a token get access, however with above now only TokenHasReadWriteScope users have access.

Has anyone else had this issue, whats going on here?

I need both type of users to have access.

This is how my view looks:

class SomeList(PermissionMixin, generics.ListCreateAPIView)

    queryset = Award.objects.all()
    serializer_class = AwardSerializer

PS TokenHasReadWriteScope is from django-oauth-toolkit

like image 936
Prometheus Avatar asked Jul 22 '14 09:07

Prometheus


People also ask

How do I use custom permissions in Django REST framework?

Create custom permission classes. Explain when to use has_permission and has_object_permission in your custom permission classes. Return a custom error message when a permission is denied. Combine and exclude permission classes using AND, OR, and NOT operators.

What is permission in Django REST framework?

Permissions are used to grant or deny access for different classes of users to different parts of the API. The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.

How do I give permission in Django?

With Django, you can create groups to class users and assign permissions to each group so when creating users, you can just assign the user to a group and, in turn, the user has all the permissions from that group. To create a group, you need the Group model from django. contrib. auth.


2 Answers

The behavior you are experiencing is absolutely normal, that's how DRF was designed. If you want to have at least one of those permission classes, you need to specify a more 'complex' condition. This is a very good example of what you might use. After you install it, you can use it like this:

from rest_condition import Or
...
permission_classes = (Or(permissions.IsAdminUser, TokenHasReadWriteScope),)
like image 119
AdelaN Avatar answered Oct 05 '22 18:10

AdelaN


With version 3.9 and above of Django Rest Framework, they have built-in support for composable permission classes and you can use and/or-operators out of the box:

permission_classes = [IsAuthenticated & (ReadOnly | IsAdmin)]
like image 22
Neman Avatar answered Oct 05 '22 17:10

Neman