如何在Django Rest Framework简单JWT中使用访问和刷新令牌返回自定义数据来标识用户? [英] How to return custom data with Access and Refresh Tokens to identify users in Django Rest Framework simple JWT?
问题描述
在Django中,超级用户可以根据其角色添加更多用户。我正在使用带有DRF的简单JWT进行身份验证。但是,仅通过查看访问和刷新令牌就无法检测用户的类型。
这是我的settings.py文件
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_AUTHENTICATION_CLASSES':('rest_framework_simplejwt.authentication.JWTAuthentication',),
}
urls.py
from django.contrib import admin
$ p当我击中127.0.0.1:8000/api/tok时$ p>
from django.urls导入路径,包括
from rest_framework_simplejwt.views import TokenObtainPairView,TokenRefreshView
urlpatterns = [
path('admin /',admin.site.urls),
path('',include('Manage_Merchants.urls')),
path('api-auth',include('rest_framework.urls')),
path('api / token /',TokenObtainPairView.as_view(),name ='token_obtain_pair'),
path( 'api / token / refresh /',TokenRefreshView.as_view(),name ='token_refresh'),
]
zh /通过邮递员,它要求输入用户名和密码。当我输入用户名和密码时,它将生成一个刷新和访问令牌。
使用邮递员用DRF生成JWT
那么我如何识别为超级用户或其他用户创建的超级用户生成的令牌?如何在字典中传递更多价值以及访问和刷新令牌来标识用户类型?
解决方案在版本中
djangorestframework-simplejwt == 4.4.0
是方法validate
而不是to_representation
,意思是:
在您的
serializer.py
中,您需要覆盖TokenObtainPairSerializer
以便包含您要在响应中发送的所有数据from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
类CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self,attrs):
#默认结果(访问/ refresh令牌)
data = super(CustomTokenObtainPairSerializer,self).validate(attrs)
#要包含的自定义数据
data.update({'user':self.user.username })
data.update({'id':self.user.id})
#以及您要在响应中发送的所有其他内容
返回数据
现在在您的
views.py
中,您需要覆盖TokenObtainPairView才能将其与新的序列化器配对。从.serializers导入CustomTokenObtainPairSerializer
类CustomTokenObtainPairView(TokenObtainPairView):
#用您的自定义
替换序列化器serializer_class = CustomTokenObtainPairSerializer
现在将其映射到您的
url.py
from rest_framework_simplejwt.views从导入TokenRefreshView,TokenVerifyView
。导入视图
urlpatterns = [
#现在,该视图具有与自定义序列化程序映射的自定义视图,其中包括所需数据
path('token /',views.CustomTokenObtainPairView。 as_view(),name ='token_obtain_pair'),
path('token / refresh /',TokenRefreshView.as_view(),name ='token_refresh'),
path('token / verify /', TokenVerifyView.as_view(),name ='token_verify')
]
In Django, superuser can add more user according to their roll. I'm using simple JWT with DRF for authentication. But it is impossible to detect the type of user only by seeing the Access and Refresh Tokens.
Here are my settings.py file
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',), }
urls.py
from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('admin/', admin.site.urls), path('', include('Manage_Merchants.urls')), path('api-auth', include('rest_framework.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ]
when I hit on 127.0.0.1:8000/api/token/ through Postman it asks for username and password. When I put Username and Password it generates a Refresh and Access Token. Generate JWT with DRF using Postman
So how can I identify the token is generated for super user or other user created bu superuser? How can I pass more value as a dictionary along with Access and Refresh Tokens to identify the type of user?
解决方案In the version
djangorestframework-simplejwt==4.4.0
it's the methodvalidate
instead ofto_representation
, meaning:In your
serializer.py
you need to override theTokenObtainPairSerializer
in order to include all the data you want to send in the responsefrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): # The default result (access/refresh tokens) data = super(CustomTokenObtainPairSerializer, self).validate(attrs) # Custom data you want to include data.update({'user': self.user.username}) data.update({'id': self.user.id}) # and everything else you want to send in the response return data
Now in your
views.py
you need to override the TokenObtainPairView in order to pair it with the new serializer.from .serializers import CustomTokenObtainPairSerializer class CustomTokenObtainPairView(TokenObtainPairView): # Replace the serializer with your custom serializer_class = CustomTokenObtainPairSerializer
Now map your it in your
url.py
from rest_framework_simplejwt.views import TokenRefreshView, TokenVerifyView from . import views urlpatterns = [ # This one now has the custom view mapped with the custom serializer that includes the desired data path('token/', views.CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('token/verify/', TokenVerifyView.as_view(), name='token_verify') ]
这篇关于如何在Django Rest Framework简单JWT中使用访问和刷新令牌返回自定义数据来标识用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!