gpt4 book ai didi

python - 如何在 python 中正确构建 json web token

转载 作者:行者123 更新时间:2023-12-01 01:05:56 26 4
gpt4 key购买 nike

我正在尝试使用 python django 构建 Json Web token pyjwt library引用 stackoverflow 中 Madhu_Kiran_K 的建议 link

在下面的代码中,我尝试生成一个 JSON Web token ,用于存储该用户的 ID、电子邮件,并将到期日期设置为 future 2 天。我可以成功地对 token 进行编码和解码,以获取所有必需的用户信息和 token 过期时间。

我现在的要求:

1.)请问如何验证并确保客户端发送的 token 仍然有效且未被篡改。

2.)如何检查过期时间并打印消息。这是我为此所做的事情

#check if the token were tampered

if content['user_id'] =='' or content['email'] == '':
print("Invalid Token")
else:
print("Token is still valid")

#check if token has expired after 2 days

if content['exp'] > dt:
print("Token is still active")
else:
print("Token expired. Get new one")

时间过期检查返回int 和 datetime.datetime 实例之间不支持的错误消息。验证的正确方法是什么。谢谢

下面是完整代码

#!/usr/bin/python

import sys
import re
import json

from datetime import datetime, timedelta
import jwt


#https://www.guru99.com/date-time-and-datetime-classes-in-python.html
#timedelta(days=365, hours=8, minutes=15)
#'exp': int(dt.strftime('%s'))


dt = datetime.now() + timedelta(days=2)
encoded_token = jwt.encode({'user_id': "abc", 'email': "nancy@gmail.com", 'exp': dt }, 'MySECRET goes here', algorithm='HS256')
print(encoded_token)

#decode above token
decode_token=jwt.decode(encoded_token, 'MySECRET goes here', algorithms=['HS256'])

content = decode_token
print(content)
print(content['user_id'])
print('json token successfully retrieved')

if content['user_id'] =='' or content['email'] == '':
print("Invalid Token")
else:
print("Token is still valid")

#check if token has expired after 2 days

if content['exp'] > dt:
print("Token is still active")
else:
print("Token expired. Get new one")

最佳答案

您不必手动检查 token 有效性或 exp 截止日期,jwt.decode() 函数会为您验证两者>.

例如,jwt.decode() 将引发 jwt.ExpiredSignatureError exception如果 token 太旧,那么只需显式捕获即可:

try:
decode_token = jwt.decode(encoded_token, 'MySECRET goes here', algorithms=['HS256'])
print("Token is still valid and active")
except jwt.ExpiredSignatureError:
print("Token expired. Get new one")
except jwt.InvalidTokenError:
print("Invalid Token")

jwt.InvalidTokenError exception是基本异常,捕获涵盖了 token 验证失败的所有可能方式。如果您想捕获任何子类,例如 jwt.ExpiredSignatureError,请在捕获 InvalidTokenError 之前将它们放入 except ...: block 中。

请参阅usage examples documentation ,尤其是Expiration Time Claim section :

Expiration time is automatically verified in jwt.decode() and raises jwt.ExpiredSignatureError if the expiration time is in the past[.]

关于python - 如何在 python 中正确构建 json web token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55363472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com