How To Implement Simple JWT Authentication in Django Rest Framework

Blog
Spread the love

We’ll learn how to use simple JWT authentication with the Django Rest Framework. Before we understand JWT Authentication, lets understand –

What is JWT ?

JWT (JSON Web-Token) is a fairly new standard which can be used for token-based authentication. Unlike the built-in Token Authentication Scheme, JWT Authentication does not need to use a database to validate a token. Instead, it relies on cryptographic algorithms and data encoding to ensure the security and integrity of the tokens.

JWT is a single line and encoded String which have three parts: –

Let’s break down the different parts.

1.Header:  It defines type and used algorithm, It contains two keys, a token type value and algorithm value used in encoding.
For Example: –

2. Payload: The Payload of a JSON Web Token (JWT) contains claims, which are statements about the user, the token itself, or any other relevant information.
For Example: –

Signature: – The signature of a JSON Web Token (JWT) is a crucial component that ensures the token’s integrity and authenticity.
For Example: –

How Does JWT Works?

extention_2024

  • User Authentication: Client sends a post request i.e the login request with the username and password.
  • Token Generation: Once it is successfully authenticated the server/API will create a JWT token which will be signed with a secret key.
  • Token Issuance: After creating the JSON Web Token, the API will return it back to the Client Application. The client receives and stores the JWT securely. It can be stored in a cookie, local storage, or a secure token storage mechanism depending on the application type (web, mobile, etc.)
  • Token Transmission: When the client wants to access a protected resource (e.g., an API endpoint), it includes the JWT in the request headers.The token is usually included in the “Authorization” header with the “Bearer” prefix (e.g., “Bearer eyJhbGciOi…”).
  • Token Verification: After receiving the token by the client app, it is verified to ensure it is authentic and then only it will be used on every subsequent request to authenticate the user so that users do not have to send the credentials anymore.
  • Token Verification: The server receives the incoming request and extracts the JWT from the request headers. It verifies the token’s integrity and authenticity by checking the signature using the same secret key that was used to sign the token during generation. If the signature is valid, the token has not been tampered with.
  • Claims Validation: The server examines the claims in the payload, including the expiration time (exp) and any custom claims. If the token is not expired and the claims are valid, the server proceeds with the request.
  • Access Control: Once the server has successfully verified and validated the JWT, it uses the information in the payload to determine the user’s identity and make access control decisions. It can identify the user, check their permissions, and grant or deny access to the requested resource accordingly.

What is Simple JWT?

Simple JWT is used for authentication in DRF, Simple JWT provides a JSON Web Token Authentication backend for the Django REST Framework. Simple JWT is a tool used with Django REST Framework to handle user authentication using JSON Web Tokens. It comes with a basic set of features that cover common authentication needs and can be easily customized if you require additional functionality.
Before you dive into using Simple JWT, it’s essential to establish the data models that represent user information for your authentication system.

Step 1: Create Project

The very first step is creating a Django project.
We’ll use a Django’s default authentication system (User model) that is based on usernames and passwords,

Step 2 : Create API’s for the User

The next step is to add Django Rest Framework (DRF) to your project
To install DRF, use the following command:

pip install djangorestframework

then add ‘rest_framework’ in project settings.py file.

Next, we create serializers for the User model.

Now we’ll create our views for registering the user. Open views.py of app and copy the below code.

Step 3: Define URL for Views

Create a new file name urls.py in your app. And copy the below code:

Now, we have to link the urls.py file of the “app” app to the main project, To do this, modify the “urls.py” file in the project as follows:

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

urlpatterns = [
    path(‘admin/’, admin.site.urls),
    path(‘api/’,include(‘simplejwtapp.urls’)),
]

Step 4: Using Simple JWT to Login User: –

Now we’ll use Simple JWT to log in users and generate access and refresh tokens for user authentication. To get Simple JWT, install it in your project directory using the command.

pip install djangorestframework-simplejwt

After installing add ‘rest_framework_simplejwt’ in project settings.py file

Next, you need to set up your Django project to use the Simple JWT library. In the settings.py file, add rest_framework_simplejwt.authentication.JWTAuthentication to the list of authentication classes.

In the urls.py file within our app, we’ll define routes for Simple JWT, including views like TokenObtainPairView and TokenRefreshView.

We’ve completed the authentication setup for our project.
we’re ready to check if our project works correctly, and we’ll use an app called Postman for this purpose. You can begin by visiting the Postman website and setting up a new workspace.

Now, in the URL field, type http://127.0.0.1:8000/api/register.

Choose the “Body” option. Then, select the “form-data” radio button, and create a new user by entering their username and password.
And, click the “Send” button, and you’ll receive JSON data below that displays the information of the new user we just added.

extention_2024

Next, let’s log in the user we registered earlier by changing the URL to “http://127.0.0.1:8000/api/token/.”

In the “Body” section, provide the correct login credentials. After clicking the “Send” button, you’ll receive two types of tokens: an Access Token and a Refresh Token.

extention_2024

You can also adjust how Simple JWT behaves by changing settings in the settings.py file.

Now we’ll check Token authenticity:

Create a protected View in views.py

Define url for this view in app ulrs.py file: –

Now try to access this view without Access Token

You will get error message of Authentication credentials were not provided.

extention_2024

To access this view we need to provide access token for this go to the authorization section select Bearer Token and then in the Token field provide access token that you get during user login.

Then we will see the message of success that we provided in hello view

extention_2024

Nikky Kumari

Nikky Kumari

2024-05-20

0

Leave a Reply

Your email address will not be published. Required fields are marked *

Find More Blogs

Exception Handling in Java

Spread the love Introduction – Exception:An unwanted

How to add custom less file in Magento2

Spread the love Source files *.css included into layout

Spring Boot Microservices

Spread the love Microservices architecture has become

Implementation of WireMock for better testing

Spread the love WireMock is a flexible and powerful tool

Magento 2: How to selected default option in configurable options?

Spread the love Configurable products in Magento 2 allow

How To Implement Simple JWT Authentication in Django Rest Framework

Spread the love We’ll learn how to use simple JWT

Optimizing Search: Integrating Elasticsearch in Django Applications

Spread the love What is Elasticsearch? Elasticsearch is a

How to create Customer Segments

Spread the love In Magento 2, “customer

Proxy Design Pattern and Requisition List in Magento 2

Spread the love Requisition List in Magento 2 Requisition

Google Ads Conversion Tracking Through Magento Platform:

Spread the love Google Ads Conversion Tracking Through

bluethinkinc Blogs