简体   繁体   English

如何在 Firebase 和服务器之间共享令牌?

[英]How to share token between Firebase and server?

My Node.js app uses Firebase products as well as a server running in App Engine.我的 Node.js 应用程序使用 Firebase 产品以及在 App Engine 中运行的服务器。 So when a user is signed in, he should be able to authenticate on both platforms.因此,当用户登录时,他应该能够在两个平台上进行身份验证。 I used custom tokens for this.我为此使用了自定义令牌

In server, I called admin.auth().createCustomToken(uid) and sent that token to client.在服务器中,我调用admin.auth().createCustomToken(uid)并将该令牌发送给客户端。
In client, I used firebase.auth().signInWithCustomToken(token) and signed in. All good.在客户端,我使用firebase.auth().signInWithCustomToken(token)并登录。一切都很好。

I also read regarding the token exp field我还阅读了有关令牌exp字段的信息

The time, in seconds since the UNIX epoch, at which the token expires.自 UNIX 时期以来,令牌过期的时间(以秒为单位)。 ... But once you sign a user in using signInWithCustomToken(), they will remain signed in into the device until their session is invalidated or the user signs out. ...但是,一旦您使用 signInWithCustomToken() 登录用户,他们将保持登录到设备,直到他们的 session 无效或用户注销。

So the Firebase handles the token refresh and all (please correct me if I'm wrong), which I don't have to worry about.所以 Firebase 处理令牌刷新和所有(如果我错了,请纠正我),我不必担心。 Moreover, Firebase and my app uses the same keys (service account keys) to generate the token.此外,Firebase 和我的应用程序使用相同的密钥(服务帐户密钥)来生成令牌。

Custom tokens are signed JWTs where the private key used for signing belongs to a Google service account.自定义令牌是签名的 JWT,其中用于签名的私钥属于 Google 服务帐户。

So a token generated is compatible between firebase and the server.因此生成的令牌在 firebase 和服务器之间是兼容的。

Now, where I'm stuck is, I need token to authenticate to App Engine server.现在,我陷入困境的是,我需要令牌来向 App Engine 服务器进行身份验证。 How to get the latest (non-expired) token from firebase after doing a successful firebase.auth().signInWithCustomToken(token) ?成功完成firebase.auth().signInWithCustomToken(token)后,如何从 firebase 获取最新(未过期)令牌?

I could have used the token in signInWithCustomToken(token) .我本可以在signInWithCustomToken(token)中使用token But this may me expired after an hour.但这可能会在一小时后过期。 So I thought I could depend on the firebase authentication.所以我想我可以依靠 firebase 身份验证。

Thanks.谢谢。

The short-lived token that Firebase SDKs auto-refresh is called an ID token, and you can get it by calling getIDToken(false) on the user object. Firebase SDKs自动刷新的短暂令牌称为ID令牌,您可以通过在user object上调用getIDToken(false)获取。 This gives you the current ID token, so there's a chance it may expire relatively quickly - although usually not for at least 5 minutes, as the SDK requests a new ID token at that point.这为您提供了当前的 ID 令牌,因此它可能会相对较快地过期 - 尽管通常不会持续至少 5 分钟,因为 SDK 会在此时请求新的 ID 令牌。

You can also force the SDK to refresh the token by calling getIDToken(true) , which means you get a token that's valid for about an hour.您还可以通过调用getIDToken(true)强制 SDK 刷新令牌,这意味着您将获得一个有效期约为一小时的令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM