Customizing JWT response from django-rest-framework-simplejwt
添加字段到 rest-auth/login 的返回值
- For example: to customize simpleJWT response by adding username and groups,
- Override the
validate
method inTokenObtainPairSerializer
# project/views.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
# Add extra responses here
data['username'] = self.user.username
data['groups'] = self.user.groups.values_list('name', flat=True)
return data
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer
- replace the login view with customized view
# project/urls.py
from .views import MyTokenObtainPairView
urlpatterns = [
# path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
]
🔚
References:
SimpleJWT Readme
source code as below: