首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >_generate_jwt_token处的格式字符串无效

_generate_jwt_token处的格式字符串无效
EN

Stack Overflow用户
提问于 2019-02-03 21:10:21
回答 2查看 1.3K关注 0票数 5

这是我正在学习的教程,链接

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“错误。

代码语言:javascript
复制
(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“”返回一个用户。

EN

回答 2

Stack Overflow用户

发布于 2019-07-12 02:39:01

它应该是:

代码语言:javascript
复制
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

票数 6
EN

Stack Overflow用户

发布于 2019-03-18 20:53:33

我也被卡在这里了,是%s特定于平台导致了这个bug。我将is更改为%S (注意大写)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54503213

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档