<p>Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.</p>
<p>Together with <ahref="../authentication/">authentication</a> and <ahref="../throttling/">throttling</a>, permissions determine whether a request should be granted or denied access.</p>
<p>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 <code>request.user</code> and <code>request.auth</code> properties to determine if the incoming request should be permitted.</p>
<p>Permissions are used to grant or deny access for different classes of users to different parts of the API.</p>
<p>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 <code>IsAuthenticated</code> class in REST framework.</p>
<p>A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the <code>IsAuthenticatedOrReadOnly</code> class in REST framework.</p>
<h2id="how-permissions-are-determined"><aclass="toclink"href="#how-permissions-are-determined">How permissions are determined</a></h2>
<p>Permissions in REST framework are always defined as a list of permission classes.</p>
<p>Before running the main body of the view each permission in the list is checked.
If any permission check fails, an <code>exceptions.PermissionDenied</code> or <code>exceptions.NotAuthenticated</code> exception will be raised, and the main body of the view will not run.</p>
<p>When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:</p>
<li>The request was successfully authenticated, but permission was denied. <em>— An HTTP 403 Forbidden response will be returned.</em></li>
<li>The request was not successfully authenticated, and the highest priority authentication class <em>does not</em> use <code>WWW-Authenticate</code> headers. <em>— An HTTP 403 Forbidden response will be returned.</em></li>
<li>The request was not successfully authenticated, and the highest priority authentication class <em>does</em> use <code>WWW-Authenticate</code> headers. <em>— An HTTP 401 Unauthorized response, with an appropriate <code>WWW-Authenticate</code> header will be returned.</em></li>
<p>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.</p>
<p>Object level permissions are run by REST framework's generic views when <code>.get_object()</code> is called.
As with view level permissions, an <code>exceptions.PermissionDenied</code> exception will be raised if the user is not allowed to act on the given object.</p>
<p>If you're writing your own views and want to enforce object level permissions,
or if you override the <code>get_object</code> method on a generic view, then you'll need to explicitly call the <code>.check_object_permissions(request, obj)</code> method on the view at the point at which you've retrieved the object.</p>
<p>This will either raise a <code>PermissionDenied</code> or <code>NotAuthenticated</code> exception, or simply return if the view has the appropriate permissions.</p>
<p><strong>Note</strong>: With the exception of <code>DjangoObjectPermissions</code>, the provided
permission classes in <code>rest_framework.permissions</code><strong>do not</strong> implement the
methods necessary to check object permissions.</p>
<p>If you wish to use the provided permission classes in order to check object
permissions, <strong>you must</strong> subclass them and implement the
<code>has_object_permission()</code> method described in the <ahref="#custom-permissions"><em>Custom
permissions</em></a> section (below).</p>
<hr/>
<h4id="limitations-of-object-level-permissions"><aclass="toclink"href="#limitations-of-object-level-permissions">Limitations of object level permissions</a></h4>
<p>For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.</p>
<p>Often when you're using object level permissions you'll also want to <ahref="../filtering/">filter the queryset</a> appropriately, to ensure that users only have visibility onto instances that they are permitted to view.</p>
<p>Because the <code>get_object()</code> method is not called, object level permissions from the <code>has_object_permission()</code> method <strong>are not applied</strong> when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the <code>perform_create()</code> method of your ViewSet class.</p>
<p><strong>Note:</strong> when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the <strong>settings.py</strong> file.</p>
<p>Provided they inherit from <code>rest_framework.permissions.BasePermission</code>, permissions can be composed using standard Python bitwise operators. For example, <code>IsAuthenticatedOrReadOnly</code> could be written:</p>
<p>The <code>AllowAny</code> permission class will allow unrestricted access, <strong>regardless of if the request was authenticated or unauthenticated</strong>.</p>
<p>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.</p>
<p>The <code>IsAdminUser</code> permission class will deny permission to any user, unless <code>user.is_staff</code> is <code>True</code> in which case permission will be allowed.</p>
<p>This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.</p>
<p>The <code>IsAuthenticatedOrReadOnly</code> will allow authenticated users to perform any request. Requests for unauthenticated users will only be permitted if the request method is one of the "safe" methods; <code>GET</code>, <code>HEAD</code> or <code>OPTIONS</code>.</p>
<p>This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.</p>
<p>This permission class ties into Django's standard <code>django.contrib.auth</code><ahref="https://docs.djangoproject.com/en/stable/topics/auth/customizing/#custom-permissions">model permissions</a>. This permission must only be applied to views that have a <code>.queryset</code> property or <code>get_queryset()</code> method. Authorization will only be granted if the user <em>is authenticated</em> and has the <em>relevant model permissions</em> assigned. The appropriate model is determined by checking <code>get_queryset().model</code> or <code>queryset.model</code>.</p>
<p>The default behavior can also be overridden to support custom model permissions. For example, you might want to include a <code>view</code> model permission for <code>GET</code> requests.</p>
<p>To use custom model permissions, override <code>DjangoModelPermissions</code> and set the <code>.perms_map</code> property. Refer to the source code for details.</p>
<p>This permission class ties into Django's standard <ahref="https://docs.djangoproject.com/en/stable/topics/auth/customizing/#handling-object-permissions">object permissions framework</a> that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as <ahref="https://github.com/lukaszb/django-guardian">django-guardian</a>.</p>
<p>As with <code>DjangoModelPermissions</code>, this permission must only be applied to views that have a <code>.queryset</code> property or <code>.get_queryset()</code> method. Authorization will only be granted if the user <em>is authenticated</em> and has the <em>relevant per-object permissions</em> and <em>relevant model permissions</em> assigned.</p>
<ul>
<li><code>POST</code> requests require the user to have the <code>add</code> permission on the model instance.</li>
<li><code>PUT</code> and <code>PATCH</code> requests require the user to have the <code>change</code> permission on the model instance.</li>
<li><code>DELETE</code> requests require the user to have the <code>delete</code> permission on the model instance.</li>
</ul>
<p>Note that <code>DjangoObjectPermissions</code><strong>does not</strong> require the <code>django-guardian</code> package, and should support other object-level backends equally well.</p>
<p>As with <code>DjangoModelPermissions</code> you can use custom model permissions by overriding <code>DjangoObjectPermissions</code> and setting the <code>.perms_map</code> property. Refer to the source code for details.</p>
<p><strong>Note</strong>: If you need object level <code>view</code> permissions for <code>GET</code>, <code>HEAD</code> and <code>OPTIONS</code> requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the <code>DjangoObjectPermissionsFilter</code> class provided by the <ahref="https://github.com/johnthagen/django-rest-framework-guardian2"><code>djangorestframework-guardian2</code> package</a>. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.</p>
<p>The methods should return <code>True</code> if the request should be granted access, and <code>False</code> otherwise.</p>
<p>If you need to test if a request is a read operation or a write operation, you should check the request method against the constant <code>SAFE_METHODS</code>, which is a tuple containing <code>'GET'</code>, <code>'OPTIONS'</code> and <code>'HEAD'</code>. For example:</p>
<pre><code>if request.method in permissions.SAFE_METHODS:
# Check permissions for read-only request
else:
# Check permissions for write request
</code></pre>
<hr/>
<p><strong>Note</strong>: The instance-level <code>has_object_permission</code> method will only be called if the view-level <code>has_permission</code> checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call <code>.check_object_permissions(request, obj)</code>. If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising <code>PermissionDenied</code> on failure.)</p>
<p>Custom permissions will raise a <code>PermissionDenied</code> exception if the test fails. To change the error message associated with the exception, implement a <code>message</code> attribute directly on your custom permission. Otherwise the <code>default_detail</code> attribute from <code>PermissionDenied</code> will be used. Similarly, to change the code identifier associated with the exception, implement a <code>code</code> attribute directly on your custom permission - otherwise the <code>default_code</code> attribute from <code>PermissionDenied</code> will be used.</p>
<p>The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked.</p>
<p>As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:</p>
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Instance must have an attribute named `owner`.
return obj.owner == request.user
</code></pre>
<p>Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling <code>self.check_object_permissions(request, obj)</code> from the view once you have the object instance. This call will raise an appropriate <code>APIException</code> if any object-level permission checks fail, and will otherwise simply return.</p>
<p>Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the <ahref="../filtering/">filtering documentation</a> for more details.</p>
<h1id="overview-of-access-restriction-methods"><aclass="toclink"href="#overview-of-access-restriction-methods">Overview of access restriction methods</a></h1>
<p>REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations.</p>
<ul>
<li><code>queryset</code>/<code>get_queryset()</code>: Limits the general visibility of existing objects from the database. The queryset limits which objects will be listed and which objects can be modified or deleted. The <code>get_queryset()</code> method can apply different querysets based on the current action.</li>
<li><code>permission_classes</code>/<code>get_permissions()</code>: General permission checks based on the current action, request and targeted object. Object level permissions can only be applied to retrieve, modify and deletion actions. Permission checks for list and create will be applied to the entire object type. (In case of list: subject to restrictions in the queryset.)</li>
<li><code>serializer_class</code>/<code>get_serializer()</code>: Instance level restrictions that apply to all objects on input and output. The serializer may have access to the request context. The <code>get_serializer()</code> method can apply different serializers based on the current action.</li>
</ul>
<p>The following table lists the access restriction methods and the level of control they offer over which actions.</p>
<p>* A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned. <br>
** The <code>get_*()</code> methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.</p>
<p>The <ahref="https://github.com/rsinger86/drf-access-policy">Django REST - Access Policy</a> package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies. </p>
<p>The <ahref="https://github.com/niwibe/djangorestframework-composed-permissions">Composed Permissions</a> package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.</p>
<p>The <ahref="https://github.com/caxap/rest_condition">REST Condition</a> package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.</p>
<p>The <ahref="https://github.com/FJNR-inc/dry-rest-permissions">DRY Rest Permissions</a> package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.</p>
<p>The <ahref="https://github.com/computer-lab/django-rest-framework-roles">Django Rest Framework Roles</a> package makes it easier to parameterize your API over multiple types of users.</p>
<p>The <ahref="https://github.com/Pithikos/rest-framework-roles">Rest Framework Roles</a> makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.</p>
<h2id="django-rest-framework-api-key"><aclass="toclink"href="#django-rest-framework-api-key">Django REST Framework API Key</a></h2>
<p>The <ahref="https://florimondmanca.github.io/djangorestframework-api-key/">Django REST Framework API Key</a> package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. <em>machines</em>) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.</p>
<h2id="django-rest-framework-role-filters"><aclass="toclink"href="#django-rest-framework-role-filters">Django Rest Framework Role Filters</a></h2>
<p>The <ahref="https://github.com/allisson/django-rest-framework-role-filters">Django Rest Framework Role Filters</a> package provides simple filtering over multiple types of roles.</p>
<p>The <ahref="https://github.com/drf-psq/drf-psq">Django Rest Framework PSQ</a> package is an extension that gives support for having action-based <strong>permission_classes</strong>, <strong>serializer_class</strong>, and <strong>queryset</strong> dependent on permission-based rules.</p>