Firebase意外持久化匿名身份验证,可与onAuthStateChanged一起使用

Firebase意外持久化匿名身份验证,可与onAuthStateChanged一起使用,firebase,react-native,firebase-authentication,Firebase,React Native,Firebase Authentication,我一直在为React原生应用程序使用Firebase匿名身份验证,主要是为了确保用户只能读/写自己的数据(例如,在安全规则中检查auth&&auth.uid) 以前,在Firebase 2.4.2中,我的身份验证方案如下: 用户注册 firebaseRef.authAnonymously((error, authData) => { if (error) { // handle error } else { // store the token on device

我一直在为React原生应用程序使用Firebase匿名身份验证,主要是为了确保用户只能读/写自己的数据(例如,在安全规则中检查
auth&&auth.uid

以前,在Firebase 2.4.2中,我的身份验证方案如下:

  • 用户注册

    firebaseRef.authAnonymously((error, authData) => {
      if (error) {
        // handle error
      } else {
        // store the token on device
        store(authData.token);
      }
    });
    
    firebase.auth().signInAnonymously().then(user => {
      // store token
      user.getToken().then(token => store(token))
    });
    
  • 当用户稍后打开应用程序时,使用存储的令牌创建会话

    firebaseRef.authWithCustomToken(storedToken, (error) => {
      if (error) {
        // handle errors
      } else {
        // proceed
      }
    });
    
  • Firebase 2.4.2中匿名身份验证返回的令牌似乎适用于自定义身份验证

    升级到Firebase 3.1后,此流不再工作——具体来说,尝试创建一个
    signInWithCustomToken
    会话,该会话使用
    SignInnoymously
    -生成的令牌返回错误
    验证/无效自定义令牌

    然而,没有持续会话的问题似乎已经消失了。现在,使用Firebase 3.1:

  • 用户注册

    firebaseRef.authAnonymously((error, authData) => {
      if (error) {
        // handle error
      } else {
        // store the token on device
        store(authData.token);
      }
    });
    
    firebase.auth().signInAnonymously().then(user => {
      // store token
      user.getToken().then(token => store(token))
    });
    
  • 当用户稍后打开应用程序时,会话仍然可用,并调用此侦听器

    firebase.auth().onAuthStateChanged(user => {
      // user is still authenticated
    });
    

  • 我不清楚这是如何工作的,Firebase是如何持久化会话的?

    在Firebase JavaScript SDK的2.x版上,身份验证在React Native上工作,但会话信息在运行之间没有持久化。原因是本地存储(Firebase用于在浏览器中持久保存此信息)在React Native中不可用

    在Firebase JavaScript SDK的3.0版中,身份验证不再在React Native上工作


    从Firebase JavaScript SDK的3.1版开始,身份验证再次在React Native上工作。会话详细信息将保留下来。

    明白了,非常酷。由于这是匿名身份验证(因此身份验证会话的任何内容都不能更改,如电子邮件或密码),我们是否可以期望此会话无限期地持续下去?firebase.auth是否为您在两次运行之间记住一个用户?@Cherniv是的,用户凭据存储在异步存储中,如Frank的回答中所述,所以onAuthStateChanged会在重新加载时拾取它