gpt4 book ai didi

python - 如何在 Python 中解码 Firebase JWT token

转载 作者:太空狗 更新时间:2023-10-30 00:01:44 25 4
gpt4 key购买 nike

我添加了 Firebase 以允许客户端直接从 Web 应用程序客户端(浏览器)进行身份验证。我正在使用 firebase-web JS 包,效果很好。我可以在我的浏览器中看到我收到了一个包含用户信息的用户对象,包括一个 idToken

然后我需要在我的服务器后端(即 python django)上对该用户进行身份验证。在 Firebase 文档中,我找到了关于我正在尝试做的事情的操作方法,即 verify the id token .

由于他们没有受支持的 Firebase sdk for python,我需要使用第三方解决方案。我来了python-jose package在 jwt.io 网站上找到它后。这个例子看起来很简单:

jwt.decode(token, 'secret', algorithms=['RS256'])

这是我第一次使用 JWT。我不知道 'secret' 有什么用。我尝试将我的 ID token 粘贴为 token,并将来自 Firebase 控制台的 Web API key 粘贴为 secret,但出现此错误:

jose.exceptions.JWKError: RSA key format is not supported

我也尝试了 JWT debugger ,它似乎正确读取了我的大部分 ID token ,但签名验证正在寻找公钥和/或私钥,这就像 'secret' 正在逃避我。

enter image description here

我真的不知道如何找到这个 secret ,以及如何验证一般的 JWT id token 。 Firebase docs上的信息(第三方部分)是:

Finally, ensure that the ID token was signed by the private key corresponding to the token's kid claim. Grab the public key from https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com and use a JWT library to verify the signature. Use the value of max-age in the Cache-Control header of the response from that endpoint to know when to refresh the public keys.

我已尝试将整个 json blob 从该 googleapis url 粘贴到 JWT 调试器中,但仍然收到“无效签名”警报。我不明白如何使用该公钥。

python-jose 应该适用于这种方法吗?如果是这样,我应该使用什么作为 secret ?如果没有,有人可以指出我正确的方向吗?

谢谢。

最佳答案

我终于在这篇文章中找到了我一直在寻找的答案:Migrating Python backend from Gitkit to to Firebase-Auth with python-jose for token verification

自该帖子发布以来,对 python-jose 包进行了更新,这为 firebase id token 提供了更好的支持。以下是关于如何使用 python 解码 firebase id token 的一些工作代码(jose version 1.3.1):

import urllib, json
from jose import jwt

idtoken = "<id token passed to server from firebase auth>"

target_audience = "<firebase app id>"

certificate_url = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'

response = urllib.urlopen(certificate_url)
certs = response.read()
certs = json.loads(certs)

#will throw error if not valid
user = jwt.decode(idtoken, certs, algorithms='RS256', audience=target_audience)
print user

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com