python - _generate_jwt_token 处的格式字符串无效
问题描述
这是我正在关注的教程,链接
https://thinkster.io/tutorials/django-json-api/authentication
正如标题所说,我在这一行收到此错误“无效的格式字符串”:
'exp': int(dt.strftime('%s'))
_generate_jwt_token。
我查看了 strftime 的文档,没有这样的格式 '%s' 有一个大写的 S ('%S'),我将格式更改为大写的 S,但我在尝试时遇到了错误解码我得到以下错误的授权令牌
{"user": {"detail": "身份验证无效。无法解码令牌。"}}
如果我留下小写的 s,我会得到“无效的格式字符串”错误。
(authentication/backends.py)
def _authenticate_credentials(self, request, token):
"""
Try to authenticate the given credentials. If authentication is
successful, return the user and token. If not, throw an error.
"""
try:
payload = jwt.decode(token, settings.SECRET_KEY)
except:
msg = 'Invalid authentication. Could not decode token.'
raise exceptions.AuthenticationFailed(msg)
(authentication/models.py)
def _generate_jwt_token(self):
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now() + timedelta(days=60)
token = jwt.encode({
'id': self.pk,
'exp': int(dt.strftime('%s'))
}, settings.SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
我希望以下令牌“令牌 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MiwiZXhwIjo0fQ.TWICRQ6BgjWMXFMizjNAXgZ9T2xFnpGiQQuhRKtjckw”返回用户。
解决方案
它应该是:
token = jwt.encode({
'id': self.pk,
'exp': dt.utcfromtimestamp(dt.timestamp()) #CHANGE HERE
}, settings.SECRET_KEY, algorithm='HS256')
这是因为 jwt 将过期时间与 utc 时间进行比较。您可以在此处使用 jwt 调试工具仔细检查您的密钥是否正确:https ://jwt.io/
更多阅读:https ://pyjwt.readthedocs.io/en/latest/usage.html#encoding-decoding-tokens-with-hs256
推荐阅读
- json - 将 json 列表记录转换为 PowerBI 中的表值
- python-3.x - 为 jupyter notebook 安装虚拟环境内核会抛出“TypeError:'type' object is not subscriptable”
- c++ - 在向量中存储动态数组
- c# - 使用 LINQ 在数组元素内部进行分组
- .net - ReadAsStringAsync 及其导入
- reactjs - 使用 pusher 和 laravel 实时响应 Web 应用程序
- django-models - 我可以在 django 的管理站点中获取 mssql 表吗
- python - tf.boolean_mask 不接受轴参数
- docker - 使用 cAdvisor 监控 docker 容器
- javascript - 在 HTML 中定义的 DomContentLoaded 中定义的 IIFE 中使用的 Javascript 函数对象原型给出错误