Adding claims to DRF simple JWT payload(向 DRF 简单 JWT 有效负载添加声明)
问题描述
在 POST 到自定义视图时使用
因此,我们可以看到令牌的第二部分是有效负载 - 包含声明.
我探索了
<代码>{token_type":访问",exp":1590914198,jti":ad6f76af1f8e4ebe8b6cf9b480d3f662",用户 ID":11,"iat": 1590917498,用户":蒂亚戈",日期":2020-05-31"}
Using djangorestframework_simplejwt library, when POST to a custom view
#urls.py
path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'),
#views.py
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer
I'm able to get a the following access token
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTEwNjg0LCJqdGkiOiI3M2MxYmZkOWNmMGY0ZjI3OTY4MGY0ZjhlYjA1NDQ5NyIsInVzZXJfaWQiOjExfQ.5vs0LmNGseU6rtq3vuQyApupxhQM3FBAoKAq8MUukIBOOYfDAV9guuCVEYDoGgK6rdPSIq2mvcSxkILG8OH5LQ
By going to https://jwt.io/ I can see the payload is currently
{
"token_type": "access",
"exp": 1590910684,
"jti": "73c1bfd9cf0f4f279680f4f8eb054497",
"user_id": 11
}
So, we can see that the second part of the token is the payload - containing the claims.
I've explored how to add more information to the Response body and now would like to know how to customize the Payload data by adding iat claim, username and today's date.
As you already created a subclass for the desired view (MyTokenObtainPairView) and a subclass for its corresponding serializer (MyTokenObtainPairSerializer), add the following to the serializer
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
...
@classmethod
def get_token(cls, user):
token = super().get_token(user)
# Add custom claims
token['iat'] = datetime.datetime.now()
token['user'] = user.username
token['date'] = str(datetime.date.today())
return token
Then, when you POST to that same location, you'll get an access token like this
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTE0MTk4LCJqdGkiOiJhZDZmNzZhZjFmOGU0ZWJlOGI2Y2Y5YjQ4MGQzZjY2MiIsInVzZXJfaWQiOjExLCJpYXQiOjE1OTA5MTc0OTgsInVzZXIiOiJ0aWFnbyIsImRhdGUiOiIyMDIwLTA1LTMxIn0.-5U9P-WWmhlOenzCvc6b7_71Tz17LyNxe_DOMwwqH4RqrNsilVukEcZWFRGupLHRZjIvPya2QJGpiju9ujzQuw
Using JWT you can see the Payload changing accordingly
{
"token_type": "access",
"exp": 1590914198,
"jti": "ad6f76af1f8e4ebe8b6cf9b480d3f662",
"user_id": 11,
"iat": 1590917498,
"user": "tiago",
"date": "2020-05-31"
}
这篇关于向 DRF 简单 JWT 有效负载添加声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向 DRF 简单 JWT 有效负载添加声明


- 沿轴计算直方图 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01