Flask和PyJWT检索授权标头

时间:2020-01-22 14:59:00

标签: python python-3.x flask jwt

有一个REST客户端,它向服务器发出HTTP请求。 REST客户端发送包含标头的请求

Authorization=Bearer someValidBase64

现在我在Python 3.8,Flask 1.1.1,PyJWT == 1.7.1中有一个服务器应用程序。

@app.route(my_rest_end_point)
def get_service_payments():
    authorization_header = request.headers.get('Authorization')

    # It prints correctly: Bearer someValidBase64
    print("Authorization header:\n" + authorization_header)

    # Details from that header
    user_permissions = jwt.decode(authorization_header)

失败
File "/usr/local/lib/python3.7/site-packages/jwt/api_jws.py", line 188, in _load
    raise DecodeError('Invalid header padding')
jwt.exceptions.DecodeError: Invalid header padding

我尝试过的

authorization_header = request.headers.get('Authorization')
print("Authorization header:\n" + authorization_header)
cleared_header =  authorization_header[7:]
print("cleared_header:\n" + cleared_header)
user_permissions = jwt.decode(cleared_header)

它将打印

Authorization header:
Bearer someValidBase64
cleared_header:
someValidBase64

它再次失败,因为令牌本身具有结构 someValidBase64.otherValidPart 所以有一个点 .

1 个答案:

答案 0 :(得分:2)

好吧,问题是authorization_header包含值"Bearer someValidBase64"。现在,当您尝试对此进行解码时,您将面临此错误,因为前缀“ Bearer”已附加到该错误。

请确保您仅将字符串的base64部分存储在authorization_header中而没有前缀,以便您可以成功对其进行解码。

更新

据我了解,authorization_header由一个JWT令牌组成,并且由于您尝试解码JWT令牌,因此请确保您的authorization_header的格式为xxxxx.yyyyy.zzzzz 如果找到的格式不是该格式,请确保将字符串剥离,以便仅提取JWT令牌的这种格式。