我使用 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
我的 views.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
}
我想在访问令牌的有效负载中添加用户名,姓氏,我想得到;
{
"token_type": "access",
"exp": 1588329561,
"jti": "944f97343b42448fbaf5461295eb0548",
"user_id": 5,
"user": "x",
"first_name": "x",
"last_name": "x",
"is_superuser": false,
}