Revoking JWT Tokens

Follow step-by-step instructions to implement the logout feature in the full stack application.

In this course, we implemented an authentication system using JSON Web Tokens (JWTs), and because it is a stateless authentication system, most of the authentication flow is handled by the frontend. If we want to log the user out of the Postagram React application, we must clear the tokens from the local storage of the browser, and the user is automatically redirected to the login page. But even if the tokens are deleted from the browser, they are still active.

The refresh tokens have a longer lifespan, so if a hacker gets their hands on a refresh token, they can still request access tokens and make HTTP requests using someone else’s identity. To avoid that, we will add a logout feature to invalidate access and refresh tokens from the server side.

The package used to add JWT authentication on the Django REST API (djangorestframework-simplejwt) supports denylisting tokens, and that is the perfect feature for what we need here (the code will refer to this as blacklisting, but we will use denylisting to refer to the same thing). Let’s set up the required configurations for the logout feature and add the feature to the Django REST API.

Adding a logout endpoint

In this section, we will write some code on the Django application to add an endpoint for logout.

Step 1

In the settings.py file of the project, add the following entry to the INSTALLED_APPS list:

Get hands-on with 1200+ tech skills courses.