Code 401 Class 31 Reading Notes
DRF Permissions
Permissions determine whether a request should be granted or denied access, with authentication and throttling.
request.user
andrequest.auth
have authentication information to determine if the incoming requests should be permitted.
How Permissions are determined
Permissions in REST framework are always defined as a list of permission classes.
Permission checks fail, either a ‘403 Forbidden’ or a ‘401 Unauthorized’ response will be returned, according to the following rules:
- The request was successfully authenticated, but permissions were denied. - An HTTP 403 Forbidden response will be returned.
- 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. - The request was not successfully authenticated, and the highest priority authentication class does use
WWW-Authenticate
headers. - An HTTP 401 Unauthorized response, with an appropriateWWW-Authenticate
header will be returned.
Object level permissions
.get_object()
: When called, object level permissions are run by REST framework’s generic views..check_object_permissions(request, obj)
: Gets called when you override theget_object
method ona generic view. Need to call it at the view point at which you’ve retrieved the object.
Setting the permission policy
DEFAULT_PERMISSION_CLASSES
: This maybe set globally, the default permission policy.APIView
: Sets the authentication policy on a per-view, or per-viewset basis.
AP Reference
AllowAny
: A permission class that will allow unrestricted access, regardless of if the request was authenticated or unauthenticated.IsAuthenticated
: A permission class that denies permission to any unauthenticated user, and allow permission otherwise. This permission is suitable if you want your API to only be accessible to registered users.IsAdminUser
: A permission class that will deny permission to any user, unlessuser.is_staff
isTrue
.IsAuthenticatedOrReadOnly
: A permission class that 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;GET
,HEAD
, orOPTIONS
.
DjangoModelPermissions
django.contrib.auth
: A permission class that is Djangos standard model permission. Must be applied to views that have a.queryset
property orget_queryset()
method.
DjangoObject Permissions
DjangoModelPermissions
: A permission class that ties into Django’s standard object - permissions framework that allows per-object permissions on models. In order to use this permission class, you’ll also need to add permission backend that supports object-level permissions, such as django-guardian.