【问题标题】:can't decode JWT token无法解码 JWT 令牌
【发布时间】:2021-06-30 22:16:19
【问题描述】:

我从 google oauth API 收到 JWT 令牌。我可以通过 jwt.io 网站使用 RS256 算法对其进行解码。问题是如何通过python对其进行解码?我尝试使用 pyJWT 但没有运气:

import jwt
js = jwt.decode(
    "JWT staff",
    algorithms=["RS256"],
)
print(js)

我收到以下错误:

jwt.exceptions.InvalidAlgorithmError: The specified alg value is not allowed

那么,问题是什么?以及如何解码收到的 JWT?

【问题讨论】:

  • 请提供minimal reproducible example 与实际输入数据。您的代码似乎是正确的,但您的令牌的配置可能是错误的。
  • Google OAuth2 id_token JWT 包含敏感信息
  • 不,我的 PyJWT 安装似乎有问题。 jwt.exceptions.InvalidAlgorithmError: 指定的alg值是不允许的
  • 不,我忘记了一些论点。您必须提供公钥。试试这个例子pyjwt.readthedocs.io/en/stable/…
  • 谢谢,还是不行。我认为 PyJWT 依赖项有问题

标签: python jwt


【解决方案1】:

有同样的问题, 找到了这个https://github.com/jpadilla/pyjwt/blob/master/jwt/algorithms.py#L49, 需要安装密码学(诗加密码学)

【讨论】:

  • 这应该是评论而不是答案。
【解决方案2】:

好吧,我找到了如何解码 Google OAuth2.0 JWT id_token 的答案。下面是我使用的代码,它只返回解码后的有效载荷。

import base64
import json


def parse_id_token(token: str) -> dict:
    """
    Parse Google OAuth2.0 id_token payload
    """
    parts = token.split(".")
    if len(parts) != 3:
        raise Exception("Incorrect id token format")
    payload = parts[1]
    padded = payload + "=" * (4 - len(payload) % 4)
    decoded = base64.b64decode(padded)
    return json.loads(decoded)

【讨论】:

  • 所以你真的只是想解码令牌。你没有回应我上面的评论,我在上面问过这个问题。要解码,您只需拨打jwt.decode(encoded, options={"verify_signature": False}),比您在这里做的要容易得多。
  • 谢谢,我会使用你的解决方案,因为它看起来更优雅。
猜你喜欢
  • 2020-12-01
  • 2019-09-24
  • 2021-12-30
  • 2018-10-05
  • 2019-05-19
  • 2017-04-15
  • 2018-11-01
  • 1970-01-01
  • 2018-08-14
相关资源
最近更新 更多