Firebase+Expo环境下重启App后重新认证Apple登录用户的问题
问题描述
使用Firebase和Expo通过Apple登录后,App运行期间可正常访问auth.currentUser,但重启App后auth().currentUser变为null。需要实现App重启时自动重新认证用户,维持登录状态。
现有方案的问题
当前启动屏代码优先从AsyncStorage读取缓存的用户数据,跳过了Firebase Auth的自动会话恢复机制:
- 缓存的用户对象是序列化后的静态数据,并非Firebase的
User实例,后续调用Firebase Auth相关API(如获取ID Token、更新用户信息)会失效 - 直接设置组件状态的用户数据,会导致组件显示已登录,但实际Firebase Auth处于未认证状态,
auth.currentUser仍为null,出现状态不一致
解决方案
Firebase Auth默认会在本地持久化用户会话,重启App时只需通过onAuthStateChanged监听认证状态,Firebase会自动恢复用户会话,无需手动从AsyncStorage读取。
修正后的启动屏代码
async componentDidMount() { // 直接监听Firebase Auth状态变化,依赖Firebase自动会话恢复 this.unsubscribe = onAuthStateChanged(auth, (currentUser) => { console.log('ON AUTH CHANGED'); this.props.setUser(currentUser); // 可选:缓存用户信息用于快速展示UI,但核心状态以Firebase返回为准 if (currentUser) { AsyncStorage.setItem('user', JSON.stringify(currentUser)); } else { AsyncStorage.removeItem('user'); } }); } componentWillUnmount() { if (this.unsubscribe) { this.unsubscribe(); } }
Apple登录代码优化(可选)
确保登录成功后处理Firebase认证结果,完善错误捕获:
function AppleLogin() { return ( <Pressable onPress={async () => { try { const appleCredential = await AppleAuthentication.signInAsync({ requestedScopes: [ AppleAuthentication.AppleAuthenticationScope.FULL_NAME, AppleAuthentication.AppleAuthenticationScope.EMAIL, ], }); const { identityToken } = appleCredential; if (identityToken) { const provider = new OAuthProvider('apple.com'); provider.addScope('email'); provider.addScope('name'); const credential = provider.credential({ idToken: identityToken }); // 等待登录完成,可处理返回的用户凭证 const userCredential = await signInWithCredential(auth, credential); console.log('登录成功', userCredential.user); } } catch (e) { if (e.code !== 'ERR_REQUEST_CANCELED') { console.error('Apple登录失败', e); } } }}> <Image style={{ width: normalize(50), height: normalize(50) }} resizeMode="contain" source={require('./assets/login/apple.png')} /> </Pressable> ); }
关键注意事项
- 确保Firebase控制台已启用Apple登录提供商,并正确配置服务ID、重定向URI等信息
- 确保Expo项目的
app.json中配置了正确的Apple登录权限及相关参数 - 永远以Firebase的
onAuthStateChanged返回的currentUser作为认证状态的唯一判断标准,不要依赖本地缓存
内容的提问来源于stack exchange,提问作者SukhiX07
相关产品推荐
相关产品推荐

