onAuthStateChanged用于令牌刷新

时间:2017-05-09 18:40:47

标签: javascript firebase firebase-authentication

我正在使用Javascript Firebase SDK对我的用户进行身份验证,并且它正常用于“正常”登录/注销流程。 现在我还有一个开放的套接字连接和REST-Api调用,这取决于身份验证令牌的有效性。遗憾的是,当令牌过期时似乎没有调用onAuthStateChanged函数。

我的onAuthStateChanged回调函数的定义如下:

  Auth._onAuthStateChanged = function() {
    var that = this;

    return function(oUser) {
      // We can extend the User Object with values we need or want.
      if (oUser && !that._oUser) {
        that.onFirebaseSignIn(oUser);
      } else if (oUser && that._oUser && oUser.uid !== that._oUser.uid) {
        that.onFirebaseUserChanged();
      } else if (oUser && that._oUser && oUser.uid === that._oUser.uid) {
        that.onFirebaseTokenChanged();
      } else if (!oUser) {
        that.onFirebaseSignOut();
      }
    };
  };

现在类似的东西在Android中正常工作,如果令牌即将到期,也会正确通知我。 定义如下:

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        if (firebaseAuth.getCurrentUser() != null && AccountTools.getCurrentUserId() == null) {
            onFirebaseSignIn(firebaseAuth);
        } else if (firebaseAuth.getCurrentUser() != null &&
                AccountTools.getCurrentUserId() != null &&
                !AccountTools.getCurrentUserId().equals(firebaseAuth.getCurrentUser().getUid())) {
            onFirebaseUserChanged(); // This may be the same as just signIn!
        } else if (firebaseAuth.getCurrentUser() != null &&
                AccountTools.getCurrentUserId() != null &&
                AccountTools.getCurrentUserId().equals(firebaseAuth.getCurrentUser().getUid())) {
            getAuthToken(false);
        } else if (firebaseAuth.getCurrentUser() == null){
            onFirebaseSignOut();
        }
    }
};

onAuthStateChanged回调的行为是否定义不足以依赖于此?如果不。我有什么选择?每次我进行REST调用时我都需要一个有效的令牌,并且真​​的希望在进行任何REST调用之前不必总是调用getToken(),而是希望它与其他所有内容都是异步的。谢谢!

1 个答案:

答案 0 :(得分:0)

我想我在Android onAuthStateChanged的文档中理解了这句话,并认为这意味着当令牌过期时会调用该函数。相反它只是被调用然后令牌实际上改变了:

  

当前用户的令牌发生变化时

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth.AuthStateListener

我现在通过解码jwt令牌然后使用setTimeout函数和失效日期在Javascript中实现。在名为i的函数中,对令牌执行强制刷新。 这应该确保令牌始终有效。