【问题标题】:Firebase ID Token expiration in an hourFirebase ID 令牌在一小时内到期
【发布时间】:2021-03-07 02:59:40
【问题描述】:

所以我在我的 react-native 应用程序中使用 redux-saga 并尝试使用刷新令牌但没有工作,所以我的方法是在 app.js 中使用以下方法,以便专门为每个请求获取令牌并强制刷新它:

  handleResponse = async () => {
    const {dispatch} = this.store;
    await axios.interceptors.request.use(config => {
      // Important: request interceptors **must** return the request.
      console.log("refreshToken")
      let user =  firebase.auth().currentUser;
        firebase.auth().onAuthStateChanged(function(user) {   if (user) {
          console.log("auth changed: ",user)
          user.getIdToken(true).then((token) => {
                setAccessToken(token);
                config.headers.authorization = token;
              }
          );
        } else { console.log("didn't auth change") } });
      console.log("req in handle response: ",JSON.stringify(config));
      return config;
    });
    axios.interceptors.response.use(config => config, (err) => {
      if (err.response) {
        const response = err.response;
        const state = this.store.getState();
        if (
            response.status === 401
            && state.auth.isAuthenticated
        ) {
          dispatch(logout());
        }
      }
      return Promise.reject(err);
    });
  };

但它总是在一个小时后结束,给我抛出以下错误::

Firebase ID 令牌已过期。从您的客户端应用程序获取新令牌并重试(auth/id-token-expired)。有关如何检索 ID 令牌的详细信息,请参阅 https://firebase.google.com/docs/auth/admin/verify-id-tokens

所以我想知道是否有另一种方法可以尝试从我这边解决问题?

提前致谢。

【问题讨论】:

    标签: javascript react-native firebase-authentication redux-saga auth-token


    【解决方案1】:

    Firebase 身份验证令牌每小时自动刷新一次。这是 SDK 的功能,您无需执行任何操作即可启用它。

    您绝对不想为每个请求调用firebase.auth().onAuthStateChanged。这会启动一个持久监听器,并在每次使用时添加一个新回调。通常,您只需为您的应用全局添加一个侦听器,并在更新发生时使用其更新。

    如果您需要知道 SDK 何时刷新令牌以便立即获取新令牌,则应改为使用 onIdTokenChanged 设置将在每次用户令牌更改时调用的回调。同样,您应该只为您的应用全局设置其中之一,并在请求时使用其当前值。

    【讨论】:

    • 非常感谢您的详细解答!它完全有效,帮助我更好地理解了这个问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2020-02-23
    • 1970-01-01
    • 2021-01-29
    • 2021-04-06
    • 2020-12-19
    相关资源
    最近更新 更多