Django : How To Implement Token Authentication In Django And Django Rest Framework
Table of Content
Token Authentication is one of the built-in authentication system in Django Rest Framework. Token Authentication is an one time token that is generate for every newly created users, which is unique and static.
Let's Setup Token Authentication
To setup Token Authentication, just follow these steps :
- To use Token Authentication, you need to add 'rest_framework.authtoken' in INSTALLED_APPSsettings.py
- INSTALLED_APPS = [
- ...
- 'rest_framework.authtoken'
- ...
- ]
- Now your django project must be configured to use the library. In settings.py, add the authentication classes:settings.py
- REST_FRAMEWORK = [
- ...
- 'DEFAULT_AUTHENTICATION_CLASSES': (
- ...
- 'rest_framework.authentication.TokenAuthentication'
- ...
- )
- ...
- ]
Agenda
We are going to create three API's here :
- Signup Api - That will create an user.
- Login Api - That will generate a access and refresh token for authorised user.
- Student Api - That will show the student data using the access token.
1. Signup API
To create a signup API, please follow these steps :
Create a serializers.py file within your app level. Let's create a ModelSerializer for Signup.
- from rest_framework import serializers
- from django.contrib.auth.models import User
- from django.contrib.auth.hashers import make_password
- class SignupSerializer(serializers.ModelSerializer):
- """override create method to change the password into hash."""
- def create(self, validated_data):
- validated_data["password"] = make_password(validated_data.get("password"))
- return super(SignupSerializer, self).create(validated_data)
- class Meta:
- model = User
- fields = ['username','password']
Here in SignupSerializer class we have override the create method and convert our string password into hash using make_password() function.
Next open a views.py file, and Let's create a APIView class for Signup.
- from rest_framework.views import APIView
- from django.contrib.auth.models import User
- from rest_framework.response import Response
- from rest_framework import status
- from .serializers import SignupSerializer
- class SignupAPIView(APIView):
- """This api will handle signup"""
- def post(self,request):
- serializer = SignupSerializer(data = request.data)
- if serializer.is_valid():
- """If the validation success, it will created a new user."""
- serializer.save()
- res = { 'status' : status.HTTP_201_CREATED }
- return Response(res, status = status.HTTP_201_CREATED)
- res = { 'status' : status.HTTP_400_BAD_REQUEST, 'data' : serializer.errors }
- return Response(res, status = status.HTTP_400_BAD_REQUEST)
Next open an urls.py file and let's create an endpoint for signup api.
- from django.urls import path
- from . import views
- urlspatterns = [
- path("api/user/signup/", views.SignupAPIView.as_view(), name="user-signup"),
- ]
Create a signals.py file and here we are going to create token by using signals.
- from django.conf import settings
- from django.db.models.signals import post_save
- from django.dispatch import receiver
- from rest_framework.authtoken.models import Token
- @receiver(post_save, sender=settings.AUTH_USER_MODEL)
- def create_auth_token(sender, instance=None, created=False, **kwargs):
- if created:
- Token.objects.create(user=instance)
By generating token using signals is the best way. So here we actually use post_save signals, that will create a token, when new user will create.
2. Login API
Now we will going to create a Login Api that will basically generate an token, so that we can use this token to access the students data.
To create a login api, follow these steps :
Open a serializers.py file and let's create a ModelSerializer for Login.
- from rest_framework import serializers
- from django.contrib.auth.models import User
- from django.contrib.auth.hashers import make_password
- class LoginSerializer(serializers.ModelSerializer):
- username = serializers.CharField()
- class Meta:
- model = User
- fields = ['username','password']
Next, open a views.py file, and Let's create a APIView class for Login.
- from rest_framework.views import APIView
- from django.contrib.auth.models import User
- from rest_framework.response import Response
- from rest_framework import status
- from .serializers import LoginSerializer
- from rest_framework.authtoken.models import Token
- from django.contrib.auth import authenticate
- class LoginAPIView(APIView):
- """This api will handle login and return token for authenticate user."""
- def post(self,request):
- serializer = LoginSerializer(data = request.data)
- if serializer.is_valid():
- username = serializer.validated_data["username"]
- password = serializer.validated_data["password"]
- user = authenticate(request, username=username, password=password)
- if user is not None:
- """We are reterving the token for authenticated user."""
- token = Token.objects.get(user=user)
- response = {
- "status": status.HTTP_200_OK,
- "message": "success",
- "data": {
- "Token" : token.key
- }
- }
- return Response(response, status = status.HTTP_200_OK)
- else :
- response = {
- "status": status.HTTP_401_UNAUTHORIZED,
- "message": "Invalid Email or Password",
- }
- return Response(response, status = status.HTTP_401_UNAUTHORIZED)
- response = {
- "status": status.HTTP_400_BAD_REQUEST,
- "message": "bad request",
- "data": serializer.errors
- }
- return Response(response, status = status.HTTP_400_BAD_REQUEST)
Next, open an urls.py file and let's create an endpoint for login api.
- from django.urls import path
- from . import views
- urlspatterns = [
- path("api/user/login/", views.LoginAPIView.as_view(), name="user-login"),
- ]
3. Students Api
Now we will going to create our Students Api that will basically return students data.
Open a models.py file and let's define student model.
- from django.db import models
- class Student(models.Model):
- name = models.CharField(max_length = 100)
- email = models.EmailField(max_length = 277)
- created_at = models.DateTimeField(auto_now_add = True, null = True)
- updated_at = models.DateTimeField(auto_now_add = True, null = True)
- def __str__(self):
- return str(self.name)
Hit these commands to create student table.
Next open a serializers.py file and let's create a ModelSerializer for Student.
- from rest_framework import serializers
- from .models import Student
- class StudentSerializer(serializers.ModelSerializer):
- class Meta:
- model = Student
- fields = ['name','email','created_at','updated_at']
Next, open a views.py file, and Let's create a APIView class for Student.
- from rest_framework.views import APIView
- from rest_framework.response import Response
- from rest_framework import status
- from .serializers import StudentSerializer
- from .models import Student
- from rest_framework.permissions import IsAuthenticated
- class StudentAPIView(APIView):
- """This api will handle student"""
- permission_classes = [ IsAuthenticated ]
- def get(self,request):
- data = Student.objects.all()
- serializer = StudentSerializer(data, many = True)
- response = {
- "status": status.HTTP_200_OK,
- "message": "success",
- "data": serializer.data
- }
- return Response(response, status = status.HTTP_200_OK)
We have to must add the IsAuthenticated permission to our student api. It means to get the students data, ideally you need to pass the access token, that you got at the time of login.
Next, open an urls.py file and let's create an endpoint for student api.
- from django.urls import path
- from . import views
- urlspatterns = [
- path("api/students/", views.StudentAPIView.as_view(), name="api-student"),
- ]
Conclusion
This is how you can secure your api's using Token Authentication, just you need to only add IsAuthenticated to permission_classes, and set the TokenAuthentication to authenticate_classess in settings file.