IsAdminUser
The IsAdminUser permission class will allow permission to users whose user.is_staff is True. This permission class ensures that the API is accessible to trusted administrators. Let’s make use of IsAdminUser permission class. Let’s import the permission class
from rest_framework.permissions import IsAdminUser
You can replace the RobotDetail and RobotList class with the below code.
Python3
class RobotDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsAdminUser] queryset = Robot.objects. all () serializer_class = RobotSerializer name = 'robot-detail' class RobotList(generics.ListCreateAPIView): permission_classes = [IsAdminUser] queryset = Robot.objects. all () serializer_class = RobotSerializer name = 'robot-list' |
Now let’s try by providing normal user credentials. The HTTPie command is
http -a “sonu”:”sn@pswrd” :8000/robot/
Output
You can notice the message saying “You do not have permission to perform this action”. This is because the user is not an administrator. Let’s provide our super admin credentials. The HTTPie command is
http -a “admin”:”admin@123″ :8000/robot/
Output
Adding Permission in API – Django REST Framework
There are many different scenarios to consider when it comes to access control. Allowing unauthorized access to risky operations or restricted areas results in a massive vulnerability. This highlights the importance of adding permissions in APIs.
Django REST framework allows us to leverage permissions to define what can be accessed and what actions can be performed in a meaningful or common way. The permission checks always run at the beginning of every view. It uses the authentication information in the ‘request.user’ and ‘request.auth’ properties for each incoming request. If the permission check fails, then the view code will not run.
Note: Together with authentication, permissions determine whether to grant or deny access for an incoming request. In this section, we will combine Basic Authentication with Django REST framework permission to set access control. You can refer Browsable API in Django REST Framework for Models, Serializers, and Views
Let’s dig deep into the Django REST framework permissions.
- AllowAny
- IsAuthenticated
- IsAdminUser
- IsAuthenticatedOrReadOnly
- DjangoModelPermissions
- DjangoModelPermissionsOrAnonReadOnly
- DjangoObjectPermissions