这是我正在学习的教程,链接
https://thinkster.io/tutorials/django-json-api/authentication
正如标题所说,我在这一行得到了这个错误"Invalid format string“:
‘'exp':int(dt.strftime('%s'))
_generate_jwt_token的。
我查看了strftime的文档,发现没有这样的格式'%s‘,有一个大写的S ('%S'),我将格式更改为大写的S,但在尝试解码授权令牌时遇到一个错误,其中我得到了以下错误
{"user":{"detail":“鉴权无效,令牌解码失败。”}}
如果我保留小写s,我会得到"Invalid format string“错误。
(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') 我期望下面的令牌"Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MiwiZXhwIjo0fQ.TWICRQ6BgjWMXFMizjNAXgZ9T2xFnpGiQQuhRKtjckw“”返回一个用户。
发布于 2019-07-12 02:39:01
它应该是:
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
发布于 2019-03-18 20:53:33
我也被卡在这里了,是%s特定于平台导致了这个bug。我将is更改为%S (注意大写)
https://stackoverflow.com/questions/54503213
复制相似问题