JWT Authentication Using Django Rest Framework

In this Python tutorial, I will show you how to perform JWT authentication using Django Rest Framework.

Also, you will understand “What is JWT with its structure?” and how it works in detail. Additionally, you will implement all the JWT concepts by building the small Django project.

In this Django project, I will show you how to configure the project for JWT and how to generate the JWT (access and refresh token) for the user and also get the new JWT for the expired token.

JWT Authentication Using Django Rest Framework

JWT is JSON WEB TOKEN which is used to transmit the data or information as a JSON object in a secure way over the web between two parties. The JSON WEB TOKEN stores all the information required by the server to authenticate a user and the server doesn’t need to store anything, so JWT is self-contained.

Structure of JWT

JWT is made up of three parts, the header, payload, and signature. But JWT looks like the following.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.ey
JzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRzaW5mbyIsImlhdCI6MTUxNjIzOTAyMn0.vLJY0L
vtZl32DiMGSSzTpgiWYVMKDAsuflE4Q2YV5ZY

Let’s decode the above-encoded part by looking at the below picture.

JWT Authentication Using Django Rest Framework

From the above picture, you can see which one is the header, payload, and signature in the encoded part.

  • Header: It has two parts, the type and algorithm.
    • type: The type of token, in this case, is JWT.
    • algorithm: The encryption algorithm for signing that token or generating a signature, in this case, is HS256 and can be a different algorithm such as RSA, SHA256 and etc.
  • Payload: It contains the claims for that token such as to whom the token refers (user), token expiration time (exp), and issue time (iat), etc and you can also specify custom claims.
  • Signature: The signature verifies the user (who sends the request with JWT) and also ensures the integrity of the data. Basically, it ensures that information is only accessed by the authorized user. To create a signature, this information is used, the encoded header, and payload using base64UrlEncode plus secrete key and the algorithm HMACSHA256 specified within the header part.

When the header, payload, and signature are combined together, then Base64 strings are formed and each part is separated by a dot and it is called a JSON WEB TOKEN. JWT is very useful in two ways, Authorization and Information Exchange.

Working of JWT (JSON Web Token)

The request that you sent to the server, also contains the JWT. Let’s understand how working of JWT.

Working of JWT

When users send a request for login with their username and password to the server, the server verifies the user credential and creates a JWT, and returns it to the user. In reality, the server returns two JWT, the access token and the refresh token.

  • The life of the access token is around 5 min or more and the refresh token has a longer life than the access token, the lifetime of both tokens can be customized. When the access token expires, the refresh token is used to generate a new access token.

The user store that token (JWT) in local storage and in the future if the user needs to access the protected resources or any URL on the server, the user sends a request with the access token in the Authorization header to the server.

After that server receives that request with an access token and verifies the access token and identifies the user who sent the request, if it is valid, then the server gives access to the requested resources or URL.

This is how JWT works. Let’s build a small project to see JWT authentication in Django.

Create Virtual Environment

Create a virtual environment ‘jwt_env’ using the below code.

python -m venv jwt_env

Activate the env using the below code.

jwt_env\Scripts\activate

Install the Django latest version using the below command.

pip install django

Create a Django project named ‘jwt_auth’ using the below command.

django-admin startproject jwt_auth .

Also, create a Django app named ‘app_jwt_auth’ using the below code.

django-admin startapp app_jwt_auth
JWT Authentication Using Django Rest Framework Virtual Environment

Next djangorestframework_simplejwt using the below code.

pip install djangorestframework_simplejwt
Installing JWT Authentication Using Django Rest Framework

After installing the package, configure the setting.py file of your Django project for the app and the package djangorestframework_simplejwt.

Add the following line in the file setting.py file.

from datetime import timedelta

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_jwt_auth',
    'rest_framework_simplejwt'
]

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

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}
JWT Authentication Using Django Rest Framework Adding Configuration

In the above code, you can change the lifetime of the access and refresh token.

Open the ‘urls.py’ of your Dajngo project ‘jwt_auth’ and add the following JWT API endpoint as shown in the below picture.


from django.contrib import admin
from django.urls import path

from rest_framework_simplejwt.views import  TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
JWT Authentication Using Django Rest Framework Tokens Views

The package rest_framework_simplejwt.views provide the two built-in views TokenObtainPairView to generate an access and refresh token for the user and TokenRefreshView to generate the new access token for the user.

Also, install the package ‘djangorestframework’ using the below command.

pip install djangorestframework

And the package to the INSTALLED_APP section of the setting.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_jwt_auth',
    'rest_framework_simplejwt',
    'rest_framework',
]

Now run the command below to migrate the default model into the database.

python mange.py migrate

Then run the Djang server using the below code.

python manage.py runserver

After running the server go to the URL ‘http://127.0.0.1:8000/api/token/’ and you see the Django RestFramework web interface as shown in the below picture.

Token Obtain View JWT Authentication Using Django Rest Framework

After that enter any username and password and click on the button POST to generate the access and refresh token.

Token Obtain Page JWT Authentication Using Django Rest Framework Any User

When you click on the button POST, it shows the error “No active account found with the given credentials” as shown in the below picture.

JWT Authentication Using Django Rest Framework No Active Account

The above error shows that the user with that username and password doesn’t exist, so create a new user.

For example, here you will create an admin user or superuser, so for that follow the below command.

python manage.py createsuperuser

The above command asks for the username, email, password and etc, so enter the details accordingly.

JWT Authentication Using Django Rest Framework Creating User

In the above picture, you created the user named ‘admin’, so again open the URL ‘http://127.0.0.1:8000/api/token/’ and enter the username and password, then click on the button POST to generate the access and refresh token.

Valid User JWT Authentication Using Django Rest Framework

After clicking on the button POST for the user ‘admin’, the new page appears with access and refresh token for the user ‘admin’ as you can see in the below picture. Save the refresh token somewhere, you will need it later.

HTTP 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY5MjI3MTI4NCwiaWF0IjoxNjkyMTg0ODg0LCJqdGkiOiIzZmI2ZDBhZDk2MmM0NzAyODljNjQ3ODZiYzk1MjFjMyIsInVzZXJfaWQiOjF9.FLwabaKZ6yyfDKOJKU1G63n57XSaCl6r4vtgZaGVu64",
    "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjkyMTg1MTg0LCJpYXQiOjE2OTIxODQ4ODQsImp0aSI6IjU4Nzk2NDIyMTkxYzQ3NTBhZmY3YjIwZWViMjQ3YzJhIiwidXNlcl9pZCI6MX0.bmC0S7hZ9SewZc6BMUveiqzJitczwEftl4RBwwxauxA"
JWT Authentication Using Django Rest Framework  Access and Refresh Token

After the access token is expired, you need to generate a new access token using the refresh token, for that enter the following URL ‘http://127.0.0.1:8000/api/token/refresh/’, then a page appears with an input field named ‘Refresh’.

In the ‘Refresh’ field enter the refresh token of the user ‘admin’ and click on the button Post.

Refersh Token JWT Authentication Using Django Rest Framework

After clicking on the button POST, the new access token is generated for the user ‘admin’ that you can see in the below picture.

Access Token JWT Authentication Using Django Rest Framework

You have successfully generated the JWT for the user and also learned how to get the new access token using the refresh token.

Conclusion

In this Python tutorial, you learned how to implement JWT authentication in Django using the Django Rest Framework with concepts such as “What are JWT and its structure”. Also learned how JSON web token is generated, then build the Django project where you created the JWT for the user.

You may like to read: