Django : How To Secure Your API Using JWT Authentication In Django And Django Rest Framework
Table of Content
JWT (Json Web Token) is one of the most popular token based authentication system. A Third party package for JWT authentication is djangorestframework-simplejwt which is used to implement jwt auth in django project.
Installation
First we need to install simplejwt package in our system by just hitting this command in terminal.
Setup simpleJWT package
To setup djangorestframework-simplejwt package follow these steps :
- Open settings.py file and add rest_framework_simplejwt under INSTALLED_APPS.settings.py
- INSTALLED_APPS = [
- ...
- 'rest_framework_simplejwt'
- ...
- ]
- 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_simplejwt.authentication.JWTAuthentication'
- ...
- )
- ...
- ]
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"),
- ]
2. Login API
Now we will going to create a Login Api that will basically generate an access token and refresh token, so that we can use access 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, create a helpers.py file and let's create a get_tokens_for_user() function that will generate access token and refresh token for authenticate user.
- from rest_framework_simplejwt.tokens import RefreshToken
- from django.contrib.auth.models import User
- from django.contrib.auth.hashers import make_password
- def get_tokens_for_user(user):
- refresh = RefreshToken.for_user(user)
- return {
- "username": user.username,
- "refresh": str(refresh),
- "access": str(refresh.access_token)
- }
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 .helpers import get_tokens_for_user
- from django.contrib.auth import authenticate
- class LoginAPIView(APIView):
- """This api will handle login and generate access and refresh 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:
- res_data = get_tokens_for_user(User.objects.get(username=username))
- response = {
- "status": status.HTTP_200_OK,
- "message": "success",
- "data": res_data
- }
- 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 all api's using jwt token, just you need to only add IsAuthenticated to permission_classes, and set the simplejwt to authenticate_classess in settings file.