How to Use JWT Authentication using Django?

Published On: 23/11/2022 | Category: Django


Hi Dev,

I'll give you an example of jwt authentication today using the Django Rest Framework. Let's talk about a jwt authentication example using the Django Rest Framework. We will assist you by providing a django jwt authentication example using the django rest framework. You can view an example of django jwt authentication. Just a few simple steps are required to complete JWT authentication in the Django rest framework.

A JSON object can be used to securely communicate data between parties utilising the open standard known as JSON Web Token. JWT is used for stateless authentication procedures for users and providers, which means that sessions are maintained on the client side as opposed to being stored on the server. Here, we'll use Django to implement the JWT authentication mechanism.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python manage.py startapp core

Step 3 : Install a required library

First of all let’s install django and djangorestframework_simplejwt which are the necessary Python libraries.

pip install django
pip install djangorestframework_simplejwt

Step 4: Update setting.py

In this step we require to do two things in our settings.py file, One is our installed app name Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

example/settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'core',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

Step 5: Creating the Views

In this step, we need to create the views for performing the fetch record to the database.Open the core/views.py file and add:

core/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated


class HelloView(APIView):
    permission_classes = (IsAuthenticated, )

    def get(self, request):
        content = {'message': 'Welcome to Tuts-Station.com'}
        return Response(content)

Step 6: Creating URLs

In this section, we need a urls.py file within the apis app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('hello/', views.HelloView.as_view(), name ='hello'),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.urls import path, include
from rest_framework_simplejwt import views as jwt_views

urlpatterns = [
    path('api/token/',
        jwt_views.TokenObtainPairView.as_view(),
        name ='token_obtain_pair'),
    path('api/token/refresh/',
        jwt_views.TokenRefreshView.as_view(),
        name ='token_refresh'),
    path('', include('app.urls')),
]

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

The JWT is just an authorization token that should be included in all requests:

curl http://127.0.0.1:8000/hello/ -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjY5MjEwMzg4LCJqdGkiOiI2MjY2N2RkOWIyZmE0N2M4OWRmNjU0ZTVlZGYwYmNjNCIsInVzZXJfaWQiOjF9.Osp5gtBadiAoRi8_0ed2os2oQLWkPyHU34gjlbS2UC0'

By exchanging a username and password for an access token and a refresh token, the JWT can be obtained.

Postman POST request:

Postman GET request:

I Hope It will help you....