This tutorial aims to guide you through the process of implementing authentication and permissions in Django REST Framework. By the end of the tutorial, you will be able to protect your API's endpoints and manage user permissions effectively.
Authentication is the process of verifying a user's identity. In Django REST Framework, there are various methods of authentication like Basic Authentication, Token Authentication, and Session Authentication. In this tutorial, we will focus on Token Authentication.
Permissions determine whether a request should be granted or denied access. Django REST Framework provides a set of predefined permissions like IsAuthenticated
, IsAdminUser
, IsAuthenticatedOrReadOnly
. You can also create custom permissions.
First, you need to include the rest_framework.authtoken
in your INSTALLED_APPS
:
INSTALLED_APPS = [
...,
'rest_framework.authtoken',
]
Then, to set Token Authentication as your default authentication scheme, update the REST_FRAMEWORK
setting in your Django settings.py
:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
When a user successfully logs in, you can create a token for them:
from rest_framework.authtoken.models import Token
def login(request):
# authentication logic here
token = Token.objects.create(user=...)
return Response({'token': token.key})
The client must include the token in the Authorization
HTTP header for every request:
```http request
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
## 3.2 Managing User Permissions
To require that a user is authenticated to view an API endpoint, you can use `IsAuthenticated` permission. Add the `permission_classes` attribute to your view:
```python
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)
If a request from an unauthenticated user hits this endpoint, a 401 Unauthorized
response will be returned.
In this tutorial, we have discussed:
- What authentication and permissions are in the context of Django REST Framework
- How to implement Token Authentication
- How to manage user permissions using predefined permission classes
To further your understanding, you might want to explore other authentication methods and how to create custom permissions.
from rest_framework import permissions
class IsNameStartsWithA(permissions.BasePermission):
def has_permission(self, request, view):
return request.user.username.startswith('A')
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class CustomView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated, IsNameStartsWithA]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
Test this view with different users. Only users with a token and a username that starts with 'A' should be able to access it.