mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-15 06:07:41 +03:00
705 lines
36 KiB
HTML
705 lines
36 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
|
|
<head>
|
|
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
|
<meta charset="utf-8">
|
|
<title>Permissions - Django REST framework</title>
|
|
<link href="../../img/favicon.ico" rel="icon" type="image/x-icon">
|
|
<link rel="canonical" href="http://www.django-rest-framework.org/api-guide/permissions/" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<meta name="description" content="Django, API, REST, Permissions">
|
|
<meta name="author" content="Tom Christie">
|
|
|
|
<!-- Le styles -->
|
|
<link href="../../css/prettify.css" rel="stylesheet">
|
|
<link href="../../css/bootstrap.css" rel="stylesheet">
|
|
<link href="../../css/bootstrap-responsive.css" rel="stylesheet">
|
|
<link href="../../css/default.css" rel="stylesheet">
|
|
|
|
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
|
|
<!--[if lt IE 9]>
|
|
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
|
|
<![endif]-->
|
|
|
|
<script type="text/javascript">
|
|
var _gaq = _gaq || [];
|
|
_gaq.push(['_setAccount', 'UA-18852272-2']);
|
|
_gaq.push(['_trackPageview']);
|
|
|
|
(function() {
|
|
var ga = document.createElement('script');
|
|
ga.type = 'text/javascript';
|
|
ga.async = true;
|
|
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
|
|
var s = document.getElementsByTagName('script')[0];
|
|
s.parentNode.insertBefore(ga, s);
|
|
})();
|
|
</script>
|
|
|
|
<style>
|
|
#sidebarInclude img {
|
|
margin-bottom: 10px;
|
|
}
|
|
#sidebarInclude a.promo {
|
|
color: black;
|
|
}
|
|
@media (max-width: 767px) {
|
|
div.promo {
|
|
display: none;
|
|
}
|
|
}
|
|
</style>
|
|
</head>
|
|
<body onload="prettyPrint()" class="-page">
|
|
|
|
<div class="wrapper">
|
|
<div class="navbar navbar-inverse navbar-fixed-top">
|
|
<div class="navbar-inner">
|
|
<div class="container-fluid">
|
|
<a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
|
|
<a class="repo-link btn btn-inverse btn-small " rel="prev" href="../throttling/">
|
|
Next <i class="icon-arrow-right icon-white"></i>
|
|
</a>
|
|
<a class="repo-link btn btn-inverse btn-small " rel="next" href="../authentication/">
|
|
<i class="icon-arrow-left icon-white"></i> Previous
|
|
</a>
|
|
<a id="search_modal_show" class="repo-link btn btn-inverse btn-small" href="#mkdocs_search_modal" data-toggle="modal" data-target="#mkdocs_search_modal"><i class="icon-search icon-white"></i> Search</a>
|
|
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
</a>
|
|
<a class="brand" href="http://www.django-rest-framework.org">Django REST framework</a>
|
|
<div class="nav-collapse collapse">
|
|
|
|
<!-- Main navigation -->
|
|
<ul class="nav navbar-nav">
|
|
|
|
<li >
|
|
<a href="../..">Home</a>
|
|
</li>
|
|
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
|
|
<li >
|
|
<a href="../../tutorial/quickstart/">Quickstart</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/1-serialization/">1 - Serialization</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/2-requests-and-responses/">2 - Requests and responses</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/3-class-based-views/">3 - Class based views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/4-authentication-and-permissions/">4 - Authentication and permissions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/5-relationships-and-hyperlinked-apis/">5 - Relationships and hyperlinked APIs</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/6-viewsets-and-routers/">6 - Viewsets and routers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/7-schemas-and-client-libraries/">7 - Schemas and client libraries</a>
|
|
</li>
|
|
|
|
</ul>
|
|
</li>
|
|
|
|
<li class="dropdown active">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
|
|
<li >
|
|
<a href="../requests/">Requests</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../responses/">Responses</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../views/">Views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../generic-views/">Generic views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../viewsets/">Viewsets</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../routers/">Routers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../parsers/">Parsers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../renderers/">Renderers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../serializers/">Serializers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../fields/">Serializer fields</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../relations/">Serializer relations</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../validators/">Validators</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../authentication/">Authentication</a>
|
|
</li>
|
|
|
|
<li class="active" >
|
|
<a href="./">Permissions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../throttling/">Throttling</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../filtering/">Filtering</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../pagination/">Pagination</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../versioning/">Versioning</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../content-negotiation/">Content negotiation</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../metadata/">Metadata</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../schemas/">Schemas</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../format-suffixes/">Format suffixes</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../reverse/">Returning URLs</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../exceptions/">Exceptions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../status-codes/">Status codes</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../testing/">Testing</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../settings/">Settings</a>
|
|
</li>
|
|
|
|
</ul>
|
|
</li>
|
|
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
|
|
<li >
|
|
<a href="../../topics/documenting-your-api/">Documenting your API</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/api-clients/">API Clients</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/internationalization/">Internationalization</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/ajax-csrf-cors/">AJAX, CSRF & CORS</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/html-and-forms/">HTML & Forms</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/browser-enhancements/">Browser Enhancements</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/browsable-api/">The Browsable API</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/rest-hypermedia-hateoas/">REST, Hypermedia & HATEOAS</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/third-party-resources/">Third Party Resources</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/contributing/">Contributing to REST framework</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/project-management/">Project management</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.0-announcement/">3.0 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.1-announcement/">3.1 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.2-announcement/">3.2 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.3-announcement/">3.3 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.4-announcement/">3.4 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/kickstarter-announcement/">Kickstarter Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/mozilla-grant/">Mozilla Grant</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/funding/">Funding</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/release-notes/">Release Notes</a>
|
|
</li>
|
|
|
|
</ul>
|
|
</li>
|
|
|
|
|
|
</ul>
|
|
|
|
</div>
|
|
<!--/.nav-collapse -->
|
|
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="body-content">
|
|
<div class="container-fluid">
|
|
<!-- Search Modal -->
|
|
<div id="mkdocs_search_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
|
|
<div class="modal-header">
|
|
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
|
|
<h3 id="myModalLabel">Documentation search</h3>
|
|
</div>
|
|
|
|
<div class="modal-body">
|
|
<form role="form" autocomplete="off">
|
|
<div class="form-group">
|
|
<input type="text" name="q" class="form-control" placeholder="Search..." id="mkdocs-search-query">
|
|
</div>
|
|
</form>
|
|
<div id="mkdocs-search-results"></div>
|
|
</div>
|
|
|
|
<div class="modal-footer">
|
|
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="row-fluid">
|
|
<div class="span3">
|
|
<div id="table-of-contents">
|
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
|
|
|
|
|
|
|
<li class="main">
|
|
<a href="#permissions">Permissions</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#how-permissions-are-determined">How permissions are determined</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#object-level-permissions">Object level permissions</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#setting-the-permission-policy">Setting the permission policy</a>
|
|
</li>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#api-reference">API Reference</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#allowany">AllowAny</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#isauthenticated">IsAuthenticated</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#isadminuser">IsAdminUser</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#isauthenticatedorreadonly">IsAuthenticatedOrReadOnly</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#djangomodelpermissions">DjangoModelPermissions</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#djangomodelpermissionsoranonreadonly">DjangoModelPermissionsOrAnonReadOnly</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#djangoobjectpermissions">DjangoObjectPermissions</a>
|
|
</li>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#custom-permissions">Custom permissions</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#examples">Examples</a>
|
|
</li>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#third-party-packages">Third party packages</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#composed-permissions">Composed Permissions</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#rest-condition">REST Condition</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#dry-rest-permissions">DRY Rest Permissions</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#django-rest-framework-roles">Django Rest Framework Roles</a>
|
|
</li>
|
|
|
|
|
|
|
|
<div class="promo">
|
|
<hr/>
|
|
<div id="sidebarInclude">
|
|
</div>
|
|
</ul>
|
|
|
|
</div>
|
|
</div>
|
|
|
|
<div id="main-content" class="span9">
|
|
|
|
|
|
|
|
<a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/permissions.py">
|
|
<span class="label label-info">permissions.py</span>
|
|
</a>
|
|
|
|
|
|
|
|
<h1 id="permissions"><a class="toclink" href="#permissions">Permissions</a></h1>
|
|
<blockquote>
|
|
<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>— <a href="https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html">Apple Developer Documentation</a></p>
|
|
</blockquote>
|
|
<p>Together with <a href="../authentication/">authentication</a> and <a href="../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 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 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>
|
|
<h2 id="how-permissions-are-determined"><a class="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 permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:</p>
|
|
<ul>
|
|
<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>
|
|
</ul>
|
|
<h2 id="object-level-permissions"><a class="toclink" href="#object-level-permissions">Object level permissions</a></h2>
|
|
<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>For example:</p>
|
|
<pre><code>def get_object(self):
|
|
obj = get_object_or_404(self.get_queryset())
|
|
self.check_object_permissions(self.request, obj)
|
|
return obj
|
|
</code></pre>
|
|
<h4 id="limitations-of-object-level-permissions"><a class="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 <a href="../filtering/">filter the queryset</a> appropriately, to ensure that users only have visibility onto instances that they are permitted to view.</p>
|
|
<h2 id="setting-the-permission-policy"><a class="toclink" href="#setting-the-permission-policy">Setting the permission policy</a></h2>
|
|
<p>The default permission policy may be set globally, using the <code>DEFAULT_PERMISSION_CLASSES</code> setting. For example.</p>
|
|
<pre><code>REST_FRAMEWORK = {
|
|
'DEFAULT_PERMISSION_CLASSES': (
|
|
'rest_framework.permissions.IsAuthenticated',
|
|
)
|
|
}
|
|
</code></pre>
|
|
<p>If not specified, this setting defaults to allowing unrestricted access:</p>
|
|
<pre><code>'DEFAULT_PERMISSION_CLASSES': (
|
|
'rest_framework.permissions.AllowAny',
|
|
)
|
|
</code></pre>
|
|
<p>You can also set the authentication policy on a per-view, or per-viewset basis,
|
|
using the <code>APIView</code> class-based views.</p>
|
|
<pre><code>from rest_framework.permissions import IsAuthenticated
|
|
from rest_framework.response import Response
|
|
from rest_framework.views import APIView
|
|
|
|
class ExampleView(APIView):
|
|
permission_classes = (IsAuthenticated,)
|
|
|
|
def get(self, request, format=None):
|
|
content = {
|
|
'status': 'request was permitted'
|
|
}
|
|
return Response(content)
|
|
</code></pre>
|
|
<p>Or, if you're using the <code>@api_view</code> decorator with function based views.</p>
|
|
<pre><code>from rest_framework.decorators import api_view, permission_classes
|
|
from rest_framework.permissions import IsAuthenticated
|
|
from rest_framework.response import Response
|
|
|
|
@api_view(['GET'])
|
|
@permission_classes((IsAuthenticated, ))
|
|
def example_view(request, format=None):
|
|
content = {
|
|
'status': 'request was permitted'
|
|
}
|
|
return Response(content)
|
|
</code></pre>
|
|
<p><strong>Note:</strong> when you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the <strong>settings.py</strong> file.</p>
|
|
<hr />
|
|
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
|
|
<h2 id="allowany"><a class="toclink" href="#allowany">AllowAny</a></h2>
|
|
<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>
|
|
<h2 id="isauthenticated"><a class="toclink" href="#isauthenticated">IsAuthenticated</a></h2>
|
|
<p>The <code>IsAuthenticated</code> permission class will deny permission to any unauthenticated user, and allow permission otherwise.</p>
|
|
<p>This permission is suitable if you want your API to only be accessible to registered users.</p>
|
|
<h2 id="isadminuser"><a class="toclink" href="#isadminuser">IsAdminUser</a></h2>
|
|
<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>
|
|
<h2 id="isauthenticatedorreadonly"><a class="toclink" href="#isauthenticatedorreadonly">IsAuthenticatedOrReadOnly</a></h2>
|
|
<p>The <code>IsAuthenticatedOrReadOnly</code> will allow authenticated users to perform any request. Requests for unauthorised 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>
|
|
<h2 id="djangomodelpermissions"><a class="toclink" href="#djangomodelpermissions">DjangoModelPermissions</a></h2>
|
|
<p>This permission class ties into Django's standard <code>django.contrib.auth</code> <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-permissions">model permissions</a>. This permission must only be applied to views that have a <code>.queryset</code> property set. Authorization will only be granted if the user <em>is authenticated</em> and has the <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.</li>
|
|
<li><code>PUT</code> and <code>PATCH</code> requests require the user to have the <code>change</code> permission on the model.</li>
|
|
<li><code>DELETE</code> requests require the user to have the <code>delete</code> permission on the model.</li>
|
|
</ul>
|
|
<p>The default behaviour 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>
|
|
<h4 id="using-with-views-that-do-not-include-a-queryset-attribute"><a class="toclink" href="#using-with-views-that-do-not-include-a-queryset-attribute">Using with views that do not include a <code>queryset</code> attribute.</a></h4>
|
|
<p>If you're using this permission with a view that uses an overridden <code>get_queryset()</code> method there may not be a <code>queryset</code> attribute on the view. In this case we suggest also marking the view with a sentinel queryset, so that this class can determine the required permissions. For example:</p>
|
|
<pre><code>queryset = User.objects.none() # Required for DjangoModelPermissions
|
|
</code></pre>
|
|
<h2 id="djangomodelpermissionsoranonreadonly"><a class="toclink" href="#djangomodelpermissionsoranonreadonly">DjangoModelPermissionsOrAnonReadOnly</a></h2>
|
|
<p>Similar to <code>DjangoModelPermissions</code>, but also allows unauthenticated users to have read-only access to the API.</p>
|
|
<h2 id="djangoobjectpermissions"><a class="toclink" href="#djangoobjectpermissions">DjangoObjectPermissions</a></h2>
|
|
<p>This permission class ties into Django's standard <a href="https://docs.djangoproject.com/en/dev/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 <a href="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>DjangoModelPermissions</code> and setting the <code>.perms_map</code> property. Refer to the source code for details.</p>
|
|
<hr />
|
|
<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, you'll want to consider also adding the <code>DjangoObjectPermissionsFilter</code> class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.</p>
|
|
<hr />
|
|
<hr />
|
|
<h1 id="custom-permissions"><a class="toclink" href="#custom-permissions">Custom permissions</a></h1>
|
|
<p>To implement a custom permission, override <code>BasePermission</code> and implement either, or both, of the following methods:</p>
|
|
<ul>
|
|
<li><code>.has_permission(self, request, view)</code></li>
|
|
<li><code>.has_object_permission(self, request, view, obj)</code></li>
|
|
</ul>
|
|
<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.</p>
|
|
<hr />
|
|
<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.</p>
|
|
<pre><code>from rest_framework import permissions
|
|
|
|
class CustomerAccessPermission(permissions.BasePermission):
|
|
message = 'Adding customers not allowed.'
|
|
|
|
def has_permission(self, request, view):
|
|
...
|
|
</code></pre>
|
|
<h2 id="examples"><a class="toclink" href="#examples">Examples</a></h2>
|
|
<p>The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.</p>
|
|
<pre><code>from rest_framework import permissions
|
|
|
|
class BlacklistPermission(permissions.BasePermission):
|
|
"""
|
|
Global permission check for blacklisted IPs.
|
|
"""
|
|
|
|
def has_permission(self, request, view):
|
|
ip_addr = request.META['REMOTE_ADDR']
|
|
blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
|
|
return not blacklisted
|
|
</code></pre>
|
|
<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>
|
|
<pre><code>class IsOwnerOrReadOnly(permissions.BasePermission):
|
|
"""
|
|
Object-level permission to only allow owners of an object to edit it.
|
|
Assumes the model instance has an `owner` attribute.
|
|
"""
|
|
|
|
def has_object_permission(self, request, view, obj):
|
|
# Read permissions are allowed to any request,
|
|
# 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 <a href="../filtering/">filtering documentation</a> for more details.</p>
|
|
<hr />
|
|
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
|
|
<p>The following third party packages are also available.</p>
|
|
<h2 id="composed-permissions"><a class="toclink" href="#composed-permissions">Composed Permissions</a></h2>
|
|
<p>The <a href="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>
|
|
<h2 id="rest-condition"><a class="toclink" href="#rest-condition">REST Condition</a></h2>
|
|
<p>The <a href="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>
|
|
<h2 id="dry-rest-permissions"><a class="toclink" href="#dry-rest-permissions">DRY Rest Permissions</a></h2>
|
|
<p>The <a href="https://github.com/Helioscene/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 retrive per user.</p>
|
|
<h2 id="django-rest-framework-roles"><a class="toclink" href="#django-rest-framework-roles">Django Rest Framework Roles</a></h2>
|
|
<p>The <a href="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>
|
|
|
|
|
|
</div> <!--/span-->
|
|
</div> <!--/row-->
|
|
</div> <!--/.fluid-container-->
|
|
</div> <!--/.body content-->
|
|
<div id="push"></div>
|
|
</div> <!--/.wrapper -->
|
|
|
|
<footer class="span12">
|
|
<p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.
|
|
</p>
|
|
</footer>
|
|
|
|
<!-- Le javascript
|
|
================================================== -->
|
|
<!-- Placed at the end of the document so the pages load faster -->
|
|
<script src="../../js/jquery-1.8.1-min.js"></script>
|
|
<script src="../../js/prettify-1.0.js"></script>
|
|
<script src="../../js/bootstrap-2.1.1-min.js"></script>
|
|
<script src="https://fund.django-rest-framework.org/sidebar_include.js"></script>
|
|
<script>var base_url = '../..';</script>
|
|
<script src="../../mkdocs/js/require.js"></script>
|
|
<script src="../../js/theme.js"></script>
|
|
|
|
<script>
|
|
var shiftWindow = function() {
|
|
scrollBy(0, -50)
|
|
};
|
|
|
|
if (location.hash) shiftWindow();
|
|
window.addEventListener("hashchange", shiftWindow);
|
|
|
|
$('.dropdown-menu').on('click touchstart', function(event) {
|
|
event.stopPropagation();
|
|
});
|
|
|
|
// Dynamically force sidenav/dropdown to no higher than browser window
|
|
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
|
|
|
|
$(function() {
|
|
$(window).resize(function() {
|
|
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
|
|
});
|
|
});
|
|
</script>
|
|
</body>
|
|
|
|
</html> |