我使用djoser和rest_framework_simplejwt。这是我的用户模型;
class userProfile(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile")
date_joined=models.DateTimeField(auto_now_add=True)
updated_on=models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
我的视图.py为用户获取令牌在下面让步;
class CustomTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
token_obtain_pair = TokenObtainPairView.as_view()
这是serializer.py;
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super(CustomTokenObtainPairSerializer, self).validate(attrs)
data.update({'user': self.user.username})
data.update({'id': self.user.id})
data.update({'first_name': self.user.first_name})
data.update({'last_name': self.user.last_name})
data.update({'is_superuser': self.user.is_superuser})
return data
我可以像这样访问和刷新令牌。
{
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU4ODQxMDY0OCwianRpIjoiNTY2MDhhOGVjYzRiNDZhMmFjYjc0Y2VmMzE2ZGE4YTkiLCJ1c2VyX2lkIjo3fQ.gXk9y3Vq0NlB8ZpU9SFcLWAMplr4_ECTeBg5WTMAuNY",
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTg4NDA5NzQ4LCJqdGkiOiIxM2VlYzQ1MjZkMTQ0ODI4YjgxNjVkZTA0MzlmYjBmMSIsInVzZXJfaWQiOjd9.sQ1G3rur1h3yqj79ZYvzHK1o6mgtHYuzJZlh5OCyg84",
"user": "x",
"id": 5,
"first_name": "x",
"last_name": "x",
"is_superuser": false,
}
当使用jwt.io有效载荷数据对令牌进行编码时;
{
"token_type": "access",
"exp": 1588329561,
"jti": "944f97343b42448fbaf5461295eb0548",
"user_id": 5
}
我想在访问令牌的有效负载中添加用户first_name、last_name,并且ıwant to get;
{
"token_type": "access",
"exp": 1588329561,
"jti": "944f97343b42448fbaf5461295eb0548",
"user_id": 5,
"user": "x",
"first_name": "x",
"last_name": "x",
"is_superuser": false,
}
我将CustomTokenObtainPairSerizer更改为:
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
token['first_name'] = user.first_name
token['last_name'] = user.last_name
token['username'] = user.username
token['is_superuser'] = user.is_superuser
return token
如果您不想解码JWT,也可以将数据添加到响应的主体中。
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
data['first_name'] = self.user.first_name
data['last_name'] = self.user.last_name
data['username'] = self.user.username
data['is_superuser'] = self.user.is_superuser
return data