1. Understanding session and token
Here is a direct reference to the article by the person, without explaining too much
2. Token response customization
Configured in the global configuration table
'DEFAULT_AUTHENTICATION_CLASSES': [
# 指定jwt Token认证
'rest_framework_jwt.authentication.JSONWebTokenAuthentication'
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
rest_framework_jwt/views.py中
url.py of the users
Quote obtain_jwt_token
from django.urls import path
from interfaces import views
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
path('login/', obtain_jwt_token)
]
It is found that there is a post method in rest_framework_jwt/views.py:
After logging in, it is found that the output only returns the token field
If we want user_id and user_name to be output as well, we need to customize the output
Check the post method in rest_framework_jwt/views.py to call the jwt_response_payload_handler method
If you don't need to rewrite, you can directly reference it in the project setting.py file
JWT_AUTH={
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
}
Finally found jwt_response_payload_handler in rest_framework_jwt.utils.py file
So we have to rewrite this method:
Create a new handler_jwt_response.py in the utils folder of the local project
def jwt_response_payload_handler(token, user=None, request=None):
"""
Returns the response data for both the login and refresh views.
Override to return a custom response such as including the
serialized representation of the User.
Example:
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': UserSerializer(user, context={'request': request}).data
}
"""
return {
'user_id': user.id,
'user_name': user.username,
'token': token
}
After rewriting, also modify the reference path in the global configuration table
JWT_AUTH={
'JWT_RESPONSE_PAYLOAD_HANDLER':
# 'rest_framework_jwt.utils.jwt_response_payload_handler',
'utils.handler_jwt_response.jwt_response_payload_handler',
}
Run to get the desired result