python - Flask 和 PyJWT 检索授权 header

标签 python python-3.x flask jwt

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

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

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

最佳答案

嗯,问题是 authorization_header 由值 “Bearer someValidBase64” 组成。现在,当您尝试对其进行解码时,您将面临此错误,因为它附加了前缀“Bearer”。

确保仅将字符串的 Base64 部分存储在 authorization_header 中(不带前缀),以便可以成功解码。

更新:

据我了解,authorization_header 由 JWT token 组成,由于您正在尝试解码 JWT token ,因此请确保您的 authorization_header 的格式为xxxxx.yyyyy.zzzzz 如果您发现它采用除此之外的任何其他格式,请确保删除字符串,以便仅提取这种格式的 JWT token 。

关于python - Flask 和 PyJWT 检索授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59862509/

相关文章:

python-3.x - 在 python 中处理两个不同大小的数据框

python - url_for : how to look into another folder other than static

python twilio flask : index out of range

python - Matplotlib basemap 绘制纬度/经度

python - 如何在 1.4.2 版本中执行 django syncdb?

python - 扩展 print 语句/函数的功能

python - Itertools代替嵌套循环

python - 单元测试中的断言错误|响应数据表明情况并非如此

python - 将文件传递给 docker 命令

python - Pandas scatter_matrix : Labels vertical (x) and horizontal (y) without being cut-off