首页 > 解决方案 > _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”返回用户。

标签: pythondjangoconduit

解决方案


它应该是:

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


推荐阅读