【问题标题】:Can't access stsTokenManager from firebase response of createUserWithEmailAndPassword无法从 createUserWithEmailAndPassword 的 firebase 响应访问 stsTokenManager
【发布时间】:2021-02-28 09:55:35
【问题描述】:

我正在使用调用 firbase.auth().createUserWithEmailAndPassword(email, password); 的反应本机注册表单 我在 trycatch 中使用如下代码:

const result = await firebase
      .auth()
      .createUserWithEmailAndPassword(email, password);

    console.log(result.user.stsTokenManager);

如果我控制台日志result.user 我看到一个 stsTokenManager 对象,其中包含有关提供的令牌的信息,但如果我尝试控制台日志result.user.stsTokenManager 我得到未定义。 如果有人知道发生这种情况的原因以及为什么我无法访问结果中的特定对象,那就太好了。

【问题讨论】:

    标签: firebase react-native firebase-authentication


    【解决方案1】:

    对于下面的请求,变量credential 是一个UserCredential 对象。

    const credential = await firebase
      .auth()
      .createUserWithEmailAndPassword(email, password);
    

    UserCredential 由以下部分组成:

    {
      additionalUserInfo?: null | {
        isNewUser: boolean;
        profile: Object | null;
        providerId: string;
        username?: string | null
      };
      credential: AuthCredential | null;
      operationType?: string | null;
      user: User | null
    }
    

    文档:UserAuthCredential

    User 的文档中可以看出,stsTokenManager 属性不存在,因为它是一个内部属性。

    这意味着你不应该使用它。

    查看fireauth.AuthUser的源代码时,该属性实际上称为stsTokenManager_,定义为here。使用user.getStsTokenManager() 访问它,定义为here

    那么,为什么控制台将其记录为stsTokenManager?这是因为调用了fireauth.AuthUser.prototype.toJSON() 方法,该方法调用了fireauth.AuthUser.prototype.toPlainObject() 方法,其中导出为stsTokenManager,定义为here

    因此,您应该能够使用以下任一方式记录访问令牌:

    console.log(result.user.getStsTokenManager().accessToken);
    
    console.log(result.user.toPlainObject().stsTokenManager.accessToken);
    

    【讨论】:

      【解决方案2】:

      我通过将响应转换为 JSON 解决了​​这个问题

      result.user.toJSON().stsTokenManager.accessToken
      

      【讨论】:

        【解决方案3】:

        我会说非常直截了当,但这就是我解决它的方法,无论 firestore 是否没有将其公开为公共属性或方法。

        const result = await firebase
            .auth()
            .createUserWithEmailAndPassword(email, password);
        
        
            console.log(result.user['stsTokenManager']);
        

        【讨论】:

          猜你喜欢
          • 2020-02-12
          • 2020-03-26
          • 1970-01-01
          • 2018-01-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-01
          • 2017-10-09
          相关资源
          最近更新 更多