_generate_jwt_token 中的格式字符串无效

Ren*_* N_ 5 python django conduit

这是我正在关注的教程,链接

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') 
Run Code Online (Sandbox Code Playgroud)

我希望以下令牌“令牌 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MiwiZXhwIjo0fQ.TWICRQ6BgjWMXFMizjNAXgZ9T2xFnpGiQQuhRKtjckw”返回用户。

小智 6

它应该是:

token = jwt.encode({
             'id': self.pk,
             'exp': dt.utcfromtimestamp(dt.timestamp())    #CHANGE HERE
    }, settings.SECRET_KEY, algorithm='HS256')
Run Code Online (Sandbox Code Playgroud)

这是因为 jwt 将过期时间与 UTC 时间进行比较。您可以在此处使用 jwt 调试工具仔细检查您的密钥是否正确:https : //jwt.io/

更多阅读:https : //pyjwt.readthedocs.io/en/latest/usage.html#encoding-decoding-tokens-with-hs256


DJ*_*DJN 2

我也被困在这里,正是平台特定的 %s 导致了该错误。我将 is 更改为 %S(注意大写)