How To Integrate JWT in Python Django REST Framework?

How To Integrate JWT in Python Django REST Framework
Social sharing

Django REST Framework is one of the most popular Django web frameworks that has been used to build many successful projects. It provides a simple and easy-to-use interface for designing APIs and JSON web services, which is quite popular among startups. When working with the REST framework in Python, there are a few ways you can implement the JSON Web Token (JWT) type of authentication.

Contents

What Is JWT?

JWT is an encoded JSON string that is passed in headers to authenticate requests. It is usually obtained by hashing JSON data with a secret key. This means that the server doesn’t need to query the database every time to retrieve the user associated with a given token.

How JSON Web Tokens Work

When a user successfully logs in using their credentials, a JSON Web Token is obtained and saved in local storage. Whenever the user wants to access a protected URL, the token is sent in the header of the request. The server then checks for a valid JWT in the Authorization header, and if found, the user will be allowed access.

A typical content header will look like this:

Authorization: Bearer gdh676hghu

Work Flow of JWT

JWT Diagram

Advantages of JWT

  • No Session to Manage (stateless)
  • Portable
  • No Cookies Required, So It’s Very Mobile Friendly
  • Good Performance
  • JWT helps in securing APIs

Django REST Framework

Django REST framework (DRF) is an open source, mature and well supported Python/Django library that aims at building sophisticated web APIs. It is a flexible and fully-featured toolkit with modular and customizable architecture that makes possible development of both simple, turn-key API endpoints and complicated REST constructs.

Main Advantages of Django REST framework

  • Simplicity, flexibility, quality, and test coverage of source code.
  • Powerful serialization engine compatible with both ORM and non-ORM data sources.
  • Pluggable and easy to customize emitters, parsers, validators and authenticators.
  • Generic classes for CRUD operations.
  • Clean, simple, views for Resources, using Django’s new class based views.
  • Support for Model Resources with out-of-the-box default implementations and input validation (optional support for forms as input validation).
  • HTTP response handling, content type negotiation using HTTP Accept headers.

Implementing JWT in Django REST Framework

Django REST Framework comes with various default Authentication Classes. Basic Authentication, Session Authentication, and Token Authentication to name a few.

Token-based authentication is the most preferred method of implementing authentication in modern APIs. In this mechanism, the server generates a token for the authenticated user and the user has to send the token along with all the HTTP requests to identify themselves.

Install DRF and Django-rest-framework-jwt using pip

pip install djangorestframework

pip install djangorestframework-jwt

pip install django

In order to use JWT, we need to configure Django-rest-framework permissions to accept JSON Web Tokens.

In the settings.py file, add the following configurations:

REST_FRAMEWORK = {

'DEFAULT_AUTHENTICATION_CLASSES': (

'rest_framework_jwt.authentication.JSONWebTokenAuthentication',

),

}

Now add JWT API endpoint to the settings.py file as below

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')),

]

The above endpoint will be used to generate and refresh the JWT token on every API call.

We will make use of the Django-REST Framework JWT Python module we installed at the beginning of this tutorial. It adds JWT authentication support for Django Rest Framework apps.

Let’s define some configuration parameters for our tokens and how they are generated in the settings.py file.

import datetime

JWT_AUTH = {

 

'JWT_VERIFY': True,

'JWT_VERIFY_EXPIRATION': True,

'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000),

'JWT_AUTH_HEADER_PREFIX': 'Bearer',

}
  • JWT_VERIFY: It will raise a jwt. Decode Error if the secret is wrong.
  • JWT_VERIFY_EXPIRATION: Sets the expiration to True, meaning Tokens will expire after a period of time. The default time is five minutes.
  • JWT_AUTH_HEADER_PREFIX: The Authorization header value prefix that is required to be sent together with the token. We have set it as Bearer, and the default is JWT

Now you can use the JWT payload in your authentication method. Go to the views.py file and add the following code

def authenticate_user(request):

email = request.data['email']

password = request.data['password']

 

user = User.objects.get(email=email, password=password)

if user:

payload = jwt_payload_handler(user)

token = jwt.encode(payload, settings.SECRET_KEY)

user_details = {}

user_details['name'] = "%s %s" % ( user.first_name, user.last_name)

user_details['token'] = token

user_logged_in.send(sender=user.__class__,request=request, user=user)

return Response(user_details, status=status.HTTP_200_OK)

Every time the user wants to make an API request, they have to send the token in auth Headers in order to authenticate the request. You can test the API endpoint using Postman or any other API testing tools.

You can check the JWT token by using any of the PI test tools like Postman. Below is the screenshot of using postman to call the JWT API

JWTYou can find out the source code for the demo project here at Github

Conclusion

JWTs are the best way to securely exchange information between front-end and backend because they can be signed, which means we can be sure that the senders are who they say they are. The structure of a JWT allows us to verify that the content hasn’t been tampered with.

JWT makes the process of user authentication on the web much easier, providing a simpler way to exchange information between a server and a client.

The Django REST Framework is a RESTful framework for developing Django applications. It provides a high-level view on how to develop RESTful web services in Django.

Your recently viewed posts:

Anurag Pattnaik - Post Author

I help you to develop web & mobile applications according to your specific needs. I manage a skillful team of resources to deliver Ruby on Rails, iPhone & Android applications on a scheduled timeframe.

    Contact Us

    We’d love to help & work with you




    When do you want to start ?


    Enter your email address to stay up to date with the latest news.
    Holler Box

    Orange Exit pop up

    Subscribe for the latest
    trends in web and
    mobile app development
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box