Django REST FRAMEWORK
Permissions
-
Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the request.user and request.auth properties to determine if the incoming request should be permitted.
-
Permissions are used to grant or deny access for different classes of users to different parts of the API.
How permissions are determined
-
Before running the main body of the view each permission in the list is checked. If any permission check fails an exceptions.PermissionDenied or exceptions.NotAuthenticated exception will be raised, and the main body of the view will not run.
-
When the permissions checks fail either a “403 Forbidden” or a “401 Unauthorized” response will be returned, according to the following rules:
1 - The request was successfully authenticated, but permission was denied. — An HTTP 403 Forbidden response will be returned
2 - The request was not successfully authenticated, and the highest priority authentication class does not use WWW-Authenticate headers. — An HTTP 403 Forbidden response will be returned.
3 - The request was not successfully authenticated, and the highest priority authentication class does use WWW-Authenticate headers. — An HTTP 401 Unauthorized response, with an appropriate WWW-Authenticate header will be returned.
Object level permissions
-
REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.
-
Object level permissions are run by REST framework’s generic views when .get_object() is called. As with view level permissions, an exceptions.PermissionDenied exception will be raised if the user is not allowed to act on the given object.
-
If you’re writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you’ll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you’ve retrieved the object.
-
This will either raise a PermissionDenied or NotAuthenticated exception, or simply return if the view has the appropriate permissions.
def get_object(self):
obj = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"])
self.check_object_permissions(self.request, obj)
return obj
Setting the permission policy
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
API Reference
-
AllowAny
-
IsAuthenticated
-
IsAdminUser
-
IsAuthenticatedOrReadOnly
-
DjangoModelPermissions
-
DjangoModelPermissionsOrAnonReadOnly
-
DjangoObjectPermissions
-
Custom permissions