Reading-notes

Permissions

permissions determine whether a request should be granted or denied access

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.

How permissions are determined

When the permissions checks fail either a “403 Forbidden” or a “401 Unauthorized” response will be returned, according to the following rules:

Object level permissions

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.

Limitations of object level permissions

Setting the permission policy

The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example.

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

API Reference

This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.

This permission is suitable if you want your API to only be accessible to registered users.

This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.

DjangoModelPermissions

This permission class ties into Django’s standard django.contrib.auth model permissions. This permission must only be applied to views that have a .queryset property or get_queryset() method. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned.

DjangoModelPermissionsOrAnonReadOnly

Similar to DjangoModelPermissions, but also allows unauthenticated users to have read-only access to the API.

Custom permissions

To implement a custom permission, override BasePermission and implement either, or both, of the following methods:

.has_permission(self, request, view)

.has_object_permission(self, request, view, obj)

The methods should return True if the request should be granted access, and False otherwise.

Overview of access restriction methods

resources:

django-rest-framework