How does Django Rest Framework permission_classes work?

Viewed 516

I don't understand why the permission_classes attribute of a GenericView is a list. Say why is it

permission_classes = [IsAdminUser]

and not

permission_class = IsAdminUser

? Also can I put 2 or more elements in the list, if so how do I interpret this?

permission_classes = [IsAdminUser, IsAuthenticated]

Is the snippet above the same as

permission_classes = [IsAdminUser & IsAuthenticated]

? Also how should I interpret bitwise OR on the permissions?

permission_classes = [IsAdminUser | IsAuthenticated]

Thank you

2 Answers

Why this is list like permission_classes = [A, B]

Let assume the you want to check multiple condition like the authenticated user must be an admin and the HTTP request will come from 172.123.12.12/32.

That time you can use IsAdminUser and IsWhiteListedIP as permission_classes = [IsAdminUser , IsWhiteListedIP].

If you avoid list then both WhileListedIP and IsAdminUser logic is needed to implement in single class. That will compromise reuse of class. Hence, each class (WhileListedIP and IsAdminUser ) only focus on specific task; you can use those separate in views and viewset independently.

When you provide a list in permission_classes, all have to pass without any exception. So, yes, those are acting as & condition.

From DRF permission documentation

Provided they inherit from rest_framework.permissions.BasePermission, permissions can be composed using standard Python bitwise operators.

For example, IsAuthenticatedOrReadOnly could be written:

class ExampleView(APIView):
    permission_classes = [IsAuthenticated|ReadOnly]

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

Default list behavior is same as & (AND)

Related