如何在Expo Go的React Native应用中通过Google Sign-In创建Firebase用户
Expo Go中实现Firebase Auth Google登录的可行方案
完全可以继续用Expo Go实现Google登录,不用切换到裸React Native。核心是避开Firebase官方的web弹窗方案,改用Expo提供的原生认证工具对接Firebase Auth。
实现步骤
1. 配置Firebase与Google OAuth凭据
- 打开Firebase控制台,在「Authentication」→「登录方法」里启用Google登录。
- 跳转至Google Cloud平台的「API和服务」→「凭据」页面,创建Web应用类型的OAuth客户端ID(Expo Go环境需要用Web类型的ID)。
- 在该客户端ID的配置中,添加授权重定向URI:
https://auth.expo.io/@你的Expo用户名/你的项目slug(项目slug可在app.json中查看)。
2. 安装依赖
在项目根目录执行命令:
npx expo install expo-auth-session expo-google-app-auth firebase
3. 编写登录逻辑
先初始化Firebase,再通过Expo的工具获取Google认证凭证,最后传给Firebase完成登录:
import { initializeApp } from 'firebase/app'; import { getAuth, signInWithCredential, GoogleAuthProvider } from 'firebase/auth'; import * as Google from 'expo-google-app-auth'; // 初始化Firebase(替换成你的项目配置) const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_SENDER_ID", appId: "YOUR_APP_ID" }; const app = initializeApp(firebaseConfig); const auth = getAuth(app); // Google登录函数 const handleGoogleSignIn = async () => { try { const loginResult = await Google.logInAsync({ webClientId: "你创建的Web OAuth客户端ID", scopes: ['profile', 'email'], // 如果需要支持iOS/Android独立应用,可添加对应客户端ID,Expo Go测试时可忽略 // iosClientId: "YOUR_IOS_CLIENT_ID", // androidClientId: "YOUR_ANDROID_CLIENT_ID" }); if (loginResult.type === 'success') { const { idToken, accessToken } = loginResult; const googleCredential = GoogleAuthProvider.credential(idToken, accessToken); // 完成Firebase登录 await signInWithCredential(auth, googleCredential); console.log('登录成功,当前用户:', auth.currentUser); } else { console.log('用户取消登录'); } } catch (err) { console.error('登录失败:', err); } };
4. 关键注意事项
- Expo Go无需手动配置
google-services.json或GoogleService-Info.plist,Expo会自动处理原生层的配置。 - 必须确保重定向URI和Google Cloud的OAuth客户端配置完全一致,否则会出现认证失败。
- 测试时如果遇到权限报错,检查Firebase是否已启用Google登录,以及客户端ID是否输入正确。
内容的提问来源于stack exchange,提问作者JBrown
相关产品推荐
相关产品推荐

