Search⌘ K
AI Features

User Logout and Token Blocklisting

Understand how to securely log out users in Django RESTful APIs by blocklisting JWT refresh tokens and adjusting token expiration times. Learn to create serializers and views for token invalidation, set permissions, and test the logout endpoint for enhanced security.

User logout

Users who log in using JWT are given access and refresh tokens. They have to use the access token whenever they make requests to protected resources. When it expires, they can renew it using the refresh token. To log out a user in our system, we must ensure that the JWTs they possess cannot get used for accessing the protected resources. However, we can still provide users with new JWTs if they log in again.

We can accomplish that by reducing the expiration time of an access token and blocklisting the refresh token. Blocklisting is adding the token to a list of unusable tokens. That makes it impossible for users to request a new access token using their current refresh token.

Note: We use the term “blocklisting,” but the Simple JWT package below uses “blacklisting.” These terms mean the same thing.

Setting up the blocklisting app

The Simple JWT package comes with a token blocklisting app. To activate it, we must add it to our list of INSTALLED_APPS in the settings.py file in our project-level directory.

Python 3.8
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'main',
'rest_framework_simplejwt.token_blacklist', # new
]

After adding the app to the list, we need to run migrations to add its models to the database schema using the command below:

py manage.py migrate
...