【发布时间】:2016-11-05 01:38:11
【问题描述】:
我一直在为 React Native 应用程序使用 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); } }); -
当用户稍后打开应用程序时,使用存储的令牌创建会话
firebaseRef.authWithCustomToken(storedToken, (error) => { if (error) { // handle errors } else { // proceed } });
Firebase 2.4.2 中匿名身份验证返回的令牌似乎适用于自定义身份验证。
升级到 Firebase 3.1 后,此流程不再有效 - 具体而言,尝试使用 signInAnonymously 生成的令牌创建 signInWithCustomToken 会话会返回错误 auth/invalid-custom-token。
但是,没有持久会话的问题似乎已经消失了。现在,使用 Firebase 3.1:
-
用户注册
firebase.auth().signInAnonymously().then(user => { // store token user.getToken().then(token => store(token)) }); -
每当用户稍后打开应用程序时,会话仍然可用,并且会调用此侦听器
firebase.auth().onAuthStateChanged(user => { // user is still authenticated });
我不清楚这是如何工作的,Firebase 如何保持会话?
【问题讨论】:
-
firebase.auth' 是否为您记住了运行之间的用户?
-
@Cherniv 是的,用户凭据存储在异步存储中,如下面弗兰克的回答中所述,因此 onAuthStateChanged 在重新加载时会拾取它
标签: firebase react-native firebase-authentication