How to Integrate JWT in Django

Introduction to JWT

JWT (JSON Web Token) is a popular cross - domain authentication solution. It can securely transmit user identity information in the token, implementing a stateless authentication mechanism.

Advantages:

  • Cross - domain authentication, suitable for distributed microservices
  • Reduces database queries and optimizes performance
  • Better hosting and scalability

Structure:

1
header.payload.signature
  • The header describes metadata such as the signature algorithm.
  • The payload contains custom user data, such as username, role, etc.
  • The signature is signed through the header, payload, and a secret key to ensure integrity and verifiability.

For the specific content of this part, you can refer to: https://www.bilibili.com/video/BV1Sz4y1o7E8. I recommended this tutorial before.

In this way, JWT can securely transfer user information between the client and the server.

Using JWT in Django

There are multiple third - party packages available to implement JWT in Django. Here, I choose to use the relatively common simplejwt.

1. Installation

1
pip install djangorestframework_simplejwt

2. Configuration

Add the following content to settings.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
INSTALLED_APPS = [ 
# ...
'rest_framework',
'rest_framework_simplejwt',
# ...
]

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

SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}

Note: The authentication - related configuration of REST_FRAMEWORK itself also needs to be configured here.

3. Add Authentication Interfaces

We need to configure URLs for the views to obtain tokens. These views are already provided by djangorestframework_simplejwt, and we just need to add them to the urls.py file:

1
2
3
4
5
6
7
8
9
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
# ...
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
# ...
]

Client - side Use of JWT

1. Obtain a New Token

Send the username and password to obtain the access and refresh tokens:

1
2
3
4
5
6
`import requests 
url = '/api/token/'
data = {'username': 'user1', 'password': 'secure - password'}
response = requests.post(url, data=data)
access_token = response.json()['access']
refresh_token = response.json()['refresh']

Save the tokens for subsequent use.

2. Call the API

Provide the JWT token in the request header:

1
2
3
headers = {'Authorization': f'Bearer {access_token}'}

response = requests.get('/api/user/', headers=headers)

3. Refresh the Token

After the access token expires, use the refresh token to obtain a new access token:

1
2
3
4
5
url = '/api/token/refresh/'
data = {'refresh': refresh_token}

response = requests.post(url, data=data)
new_access_token = response.json()['access']

Repeat steps 2 and 3 to call the API with the new token.

So far, we have learned how to integrate JWT authentication in the Django REST framework to achieve token - based API access control. JWT can provide a more powerful user authentication solution.