如何在Python

时间:2016-11-28 08:25:36

标签: python firebase jwt firebase-authentication python-jose

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

然后我需要在我的服务器后端验证这个用户,这是python django。在Firebase文档中,我找到了我正在尝试做的操作方法,即verify the id token

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

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

这是我第一次使用JWT。我不知道'secret'使用什么。我尝试将我的ID令牌粘贴为token,并将Fire API控制台中的Web API密钥粘贴为secret,但出现此错误:

  

jose.exceptions.JWKError:不支持RSA密钥格式

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

enter image description here

我真的不知道如何找到这个秘密,以及如何验证JWT id令牌。 Firebase docs(第三方部分)的信息是:

  

最后,确保ID令牌由私钥签名   对应于令牌的孩子声称。从中获取公钥   https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com   并使用JWT库来验证签名。使用的值   来自该端点的响应的Cache-Control标头中的max-age   知道何时刷新公钥。

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

python-jose应该采用这种方法吗?如果是这样,我应该用什么秘密?如果没有,有人可以指出我正确的方向吗?

感谢。

1 个答案:

答案 0 :(得分:5)

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

自帖子发布以来,对python-jose包进行了更新,这为firebase id令牌提供了更好的支持。以下是一些有关如何使用python解码firebase id令牌的工作代码(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