python - 使用 PyJWT 在 Python 中解码 Firebase JWT

标签 python firebase firebase-authentication jwt pyjwt

我写了下面的代码:

def check_token(token):
    response = requests.get("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com")
    key_list = response.json()
    decoded_token = jwt.decode(token, key=key_list, algorithms=["RS256"])
    print(f"Decoded token : {decoded_token}")

我正在尝试解码 firebase 客户端提供的 token 以在服务器端验证它。
上面的代码抛出以下异常:

TypeError: Expecting a PEM-formatted key.

我尝试不将列表传递给 jwt.decode 方法,只传递关键内容,我有一个更大的错误,即库 无法反序列化 Key .
我在关注这个answer但是我收到了这个错误。

requests转换问题吗?我做错了什么?

最佳答案

decode() 中的第二个参数key 似乎采用字符串值而不是列表。 Google API 请求返回一个包含多个键的字典/ map 。流程如下:

  1. 从 Google API 端点获取公钥
  2. 然后 read headers without validation获取 kid 声明然后使用它从该字典中获取适当的 key
  3. 这是一个X.509 证书 而不是this answer 中的公钥所以你需要从中获取公钥。

以下功能对我有用:

import jwt
import requests
from cryptography.hazmat.backends import default_backend
from cryptography import x509

def check_token(token):
    n_decoded = jwt.get_unverified_header(token)
    kid_claim = n_decoded["kid"]

    response = requests.get("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com")
    x509_key = response.json()[kid_claim]
    key = x509.load_pem_x509_certificate(x509_key.encode('utf-8'),  backend=default_backend())
    public_key = key.public_key()

    decoded_token = jwt.decode(token, public_key, ["RS256"], options=None, audience="<FIREBASE_PROJECT_ID>")
    print(f"Decoded token : {decoded_token}")

check_token("FIREBASE_ID_TOKEN")

关于python - 使用 PyJWT 在 Python 中解码 Firebase JWT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69319437/

相关文章:

java - 如何使用 Content Provider 将文件放入 firebase (内容 ://) as source?

javascript - Firebase 函数 - 在用户获取中获取实时数据库后返回

javascript - Firestore 文档 typescript doc.data() 未定义?

java - 注册后存储用户的电子邮件和密码

python - 使用 numba JIT 加速函数时遇到问题

Python flask : I have a flask middleware in which I want to calculate the time taken by the requests and add it to the header of the response

python - Python中的购物 list

python - 如何基于相同的日期时间 x 轴同时绘制两个不同的数据框列

ios - 重置密码时将用户重定向到 iOS 应用程序

firebase 电话认证 "We have blocked all requests from this device due to unusual activity. Try again later."