【问题标题】:How to send and receive JWT token?如何发送和接收 JWT 令牌?
【发布时间】:2018-07-12 05:24:00
【问题描述】:

尝试验证用户的令牌。

我如何在客户端发出请求(js + react):

axios({
        method: 'POST',
        url: '/verify', 
        headers: { authorization: sessionStorage.getItem('token') },
        data: {}
    })
        .then(function(response) {
            // ...
        });

我如何在服务器端(python)接收请求:

@app.route('/verify', methods=['POST'])
def verify_user():
    token = request.headers.get('Authorization')
    payload = jwt.decode(token, SECRET_KEY)  // error here
    // ...

为什么会出现此错误? :

Traceback (most recent call last):
........
jwt.exceptions.DecodeError: Signature verification failed

提前谢谢你。

附言令牌发送正确


编辑:

找到错误的原因:

@app.route('/login', methods=['POST'])
def get_user():
    // ...
    token = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
    return token // when I return the token here, it becomes slightly reduced

真实代币:

b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U'

我返回的缩减令牌:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U

我需要如何将生成的 jwt 令牌发送给客户端来解决这个问题?

【问题讨论】:

  • 如果令牌发送正确,有什么问题?未验证签名并不是真正的错误
  • @azium 就是不明白,为什么没有验证签名...
  • 确保正确编码和解码
  • 如果没有示例说明令牌在发送之前的样子以及它到达服务器端时的样子,很难帮助您解决此问题。您能否将该信息添加到您的帖子中?
  • @MattMorgan 已编辑,谢谢。它成功到达服务器。我只是无法在客户端发送正确的令牌。

标签: javascript python authentication jwt


【解决方案1】:

这看起来像是字符串与字节的编码问题。解码字节串:

str = byte_string.decode('UTF-8')  # turns b'123' into '123'

将字符串编码为字节:

byte_string = str.encode('UTF-8')  # turns '123' into b'123'

您可能需要将传入的字符串encode 转换为字节,然后再将其传递给jwt.decode(),如下所示:

jwt.decode(token.encode('UTF-8'), SECRET_KEY)

除了 UTF-8 之外还有其他编码,但这可能是您需要的。

【讨论】:

  • 已修复,谢谢。现在令牌完全一样,但不幸的是,我得到了同样的错误 jwt.exceptions.DecodeError: Signature verification failed
  • 哦,不,我只是使用了不同的键...再次感谢您!
  • 太棒了。我们在生产应用程序中使用 JWT,发现它们有用且易于使用。
猜你喜欢
  • 2018-12-30
  • 1970-01-01
  • 2021-01-07
  • 2019-09-27
  • 2018-06-08
  • 2019-01-06
  • 2023-03-27
  • 2017-01-02
  • 2021-07-23
相关资源
最近更新 更多