Firebase令牌到期和处理刷新令牌的最佳实践 [英] Firebase tokens expiration and best practice for handling refresh tokens

查看:64
本文介绍了Firebase令牌到期和处理刷新令牌的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用客户端上的Firebase用户身份验证方法在客户端应用程序(基于Cordova的移动应用程序)上使用Firebase:

I am currently using Firebase on a client application (Cordova based mobile app) using the firebase user authentication methods on the client:

  • signInWithEmailAndPassword
  • FacebookAuthProvider

根据我目前对会话到期的理解和经验:

From my current understanding and experience with the sessions expiring:

"身份验证会话不会随着Firebase登录而到期.但是ID令牌必须每小时刷新一次,以保持对服务的访问."

我认为这意味着我应该编写一个每59分钟运行一次并运行firebase方法的后台进程方法:

I assume this would mean I should just write a background process method that runs every 59 minutes and run the firebase method:

firebase.auth().currentUser.getIdToken(true)//true表示根据firebase文档,无论当前令牌过期如何,都强制执行Refresh.

firebase.auth().currentUser.getIdToken(true) // true indicates according to firebase docs to forceRefresh regardless of the current tokens expiration.

我只是想确保自己已经把头缠住了.

I am just looking to make sure that I have wrapped my head around this.

我正在处理像这样的简单事情……这应该可以解决问题:

I'm going with something simple like this... this should probably do the trick:

  let firebaseTokenRefresh = setInterval(function(){
     console.log('running firebase token refresh...');
     // true = forceRefresh
     firebase.auth().currentUser.getIdToken(true); 
  }, 3540000); // 59 minutes firebase token refresh (1 hr expiration)

谢谢.

推荐答案

不需要主动刷新令牌(这样做太昂贵了).每当需要ID令牌时,只需调用 user.getIdToken().这将返回缓存的未过期令牌,或者如果当前令牌已过期则刷新它.您可以在将经过身份验证的请求发送到服务器时随时调用.如果您使用的是Firestore或Realtime数据库,它们将在需要时随时为您自动刷新令牌.您可以通过 auth.onIdTokenChanged()侦听器来侦听令牌更新.

There is no need to proactively refresh the token (it is too expensive to do so). Anytime you need an ID token, you just call user.getIdToken(). This will either return the cached unexpired token or refresh it if the current one is expired. You can call that anytime you are sending an authenticated request to your server. If you are using Firestore or Realtime database, they will automatically refresh the token for you anytime they need on. You can listen to token updates via auth.onIdTokenChanged() listener.

这篇关于Firebase令牌到期和处理刷新令牌的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆