
Token Authentication in Django Rest Framework is a type of authentication mechanism used to authenticate and authorize requests made by clients to the server. It works by generating a unique token for each authenticated user and sending it along with every subsequent request made by the user.
This token serves as a credential to identify the user and grant them access to resources or services that require authentication.
Introduction
To configure Token Authentication in Django Rest Framework, add ‘rest_framework.authentication.TokenAuthentication’ to the DEFAULT_AUTHENTICATION_CLASSES list in settings.py. Once you have done this, Django will automatically handle the generation and management of tokens. Token Authentication is built-in and easily configurable in Django Rest Framework.
To use Token Authentication, the user must first log in and authenticate themselves. Once authenticated, the server generates a unique token and sends it back to the client. The client then includes this token in the Authorization header of all subsequent requests.
The server receives the token, verifies it, and grants the client access to the requested resource or service if the token is valid. Token Authentication is commonly used in RESTful APIs to protect endpoints that require authentication, such as updating user data or making purchases.
Token Authentication is a preferred choice among users compared to other authentication methods, such as session-based authentication. This is because it is stateless and doesn’t require the server to store user sessions. As a result, it becomes easier to scale the application. In addition, tokens can have an expiration time that ensures the user will need to log in again after a specific period. This provides additional security to the application.
A Simple project on token authentication in Django:
- Create a new Django project using the command
django-admin startproject myproject
. - Create a new app using the command
python manage.py startapp myapp
. - To configure authentication in Django, start by adding ‘rest_framework’ and ‘myapp’ to the INSTALLED_APPS list in the settings.py file. Then, add ‘rest_framework.authentication.TokenAuthentication’ to the DEFAULT_AUTHENTICATION_CLASSES list.Create a new model
User
inmodels.py
withusername
,password
, andemail
fields. - Create a serializer
UserSerializer
inserializers.py
withusername
,password
, andemail
fields. - Create a view
UserViewSet
inviews.py
with methodscreate
andlist
. - In
urls.py
, create a new URL pattern forUserViewSet
and set the authentication classes to use Token Authentication. - Run the migrations using the command
python manage.py makemigrations
andpython manage.py migrate
. - To start the server, first, use the command “python manage.py runserver”.
Here is the sample code for models.py
:
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
email = models.EmailField()
def __str__(self):
return self.username
Here is the sample code for serializers.py
:
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password', 'email')
extra_kwargs = {'password': {'write_only': True}}
Here is the sample code for views.py
:
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import User
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
permission_classes = [IsAuthenticated]
def create(self, request, *args, **kwargs):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
Here is the sample code for urls.py
:
from django.urls import path, include
from rest_framework import routers
from .views import UserViewSet
router = routers.DefaultRouter()
router.register('users', UserViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Great! With that complete, you can now test the project by making requests to the users endpoint using a tool such as Postman. In addition, it’s important to include the token in the Authorization header of your requests. You will ensure that you properly authenticate and authorize your requests. Furthermore, be sure to review the API documentation for any other requirements or limitations on the requests you can make.