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 | INSTALLED_APPS = [ |
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 | from django.urls import path |
Client - side Use of JWT
1. Obtain a New Token
Send the username and password to obtain the access and refresh tokens:
1 | `import requests |
Save the tokens for subsequent use.
2. Call the API
Provide the JWT token in the request header:
1 | headers = {'Authorization': f'Bearer {access_token}'} |
3. Refresh the Token
After the access token expires, use the refresh token to obtain a new access token:
1 | url = '/api/token/refresh/' |
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.