In this tutorial, you will learn how to create User Registration, Login and Logout System using Django Rest Framework. For this tutorial we will use Django Rest Knox Library for Token Based Authentication System for Rest Framework. Knox provides easy to use authentication for Django REST Framework. Knox authentication is token based, similar to the TokenAuthentication built in to DRF.

Django Rest Framework Project Setup
We will install following libraries for django, django rest framework and django rest knox.
pip install djangorestframework pip install django-rest-knox
After installing the above library. Add rest_framework
and knox
to your INSTALLED_APPS
, remove rest_framework.authtoken
if you were using it.
INSTALLED_APPS = [ ... 'rest_framework', 'knox', ]
Make knox’s TokenAuthentication your default authentification class for django-rest-framework, in settings.py
file:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', 'knox.auth.TokenAuthentication', ] }
Note – The above REST_FRAMEWORK
allows both session based and token based authentication.
User Registration API using Django Rest Framework
Now we will User Registration API Using Django Rest Framework. We will create Register Serializer for User Register API.
Create a file in your app named serializers.py
and add the bellow code –
from rest_framework import serializers from django.contrib.auth.models import User # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user
After creating serializer, we need to create DRF APIView.
In views.py
file, add the following code –
from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] })
In urls.py
file add following path –
from .views import RegisterAPI from django.urls import path urlpatterns = [ path('api/register/', RegisterAPI.as_view(), name='register'), ]
That’s it. Now go to url ( http://localhost:8000/api/register/ ) in your browser or post and the following in content.
{ "username": "admin", "email": "[email protected]", "password": "[email protected]" }
And in response, you will get similar data –
{ "user": { "id": 2, "username": "admin1", "email": "[email protected]" }, "token": "790e890d571753148bbc9c4447f106e74ecf4d1404f080245f3e259703d58b09" }
Login Logout API Authentication using Django Rest Framework
Knox provides one class to handle authentication. We will use KnoxLoginView to create login logout system.
We have already create a app with name accounts. Inside this app we will create our LoginView.
In accounts/views.py
file, add following code –
from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None)
Note – login(request, user)
line in above code, will also create session based authentication with token based authentication.
And in accounts/urls.py
file
from knox import views as knox_views from .views import LoginAPI from django.urls import path urlpatterns = [ path('api/login/', LoginAPI.as_view(), name='login'), path('api/logout/', knox_views.LogoutView.as_view(), name='logout'), path('api/logoutall/', knox_views.LogoutAllView.as_view(), name='logoutall'), ]
That’s it. Now go to url ( http://localhost:8000/api/login/ ) in your browser or post and the following in content.
{ "username": "admin", "password": "[email protected]" }
It will return in response like this –
{ "expiry": "2020-06-29T02:56:44.924698Z", "token": "99a27b2ebe718a2f0db6224e55b622a59ccdae9cf66861c60979a25ffb4f133e" }
In this tutorial you learnt to create authentication system like user registration, login and logout system using Django Rest Framework. This tutorial explain Session Based Authentication and Token Based Authentication in the Django REST Framework.
Find this tutorial on GitHub – https://github.com/studygyaan/django-rest-framework-tutorial