如何在Expo React Native应用中实现Firebase谷歌身份认证?
React Native 中 Firebase 谷歌身份认证的实现方案(非弃用版)
针对你遇到的旧包弃用问题,以下是当前官方推荐的两种主流实现方案,分别适配 Expo 托管项目和裸 React Native 项目:
一、Expo 托管项目(Managed Workflow)
使用 expo-auth-session 替代已弃用的 expo-google-app-auth,配合 Firebase 完成认证流程。
1. 安装依赖
npx expo install expo-auth-session expo-google-signin firebase
2. 平台配置
- 谷歌云控制台:创建项目并启用「Google Identity API」,生成Web 应用类型的 OAuth 2.0 客户端 ID,将 Expo 自动生成的回调地址(格式:
https://auth.expo.io/@你的用户名/项目slug)添加到「授权重定向 URI」列表。 - Firebase 控制台:进入「Authentication」→「登录方法」,启用谷歌登录,填入上述谷歌云的客户端 ID 和密钥。
3. 代码实现
初始化 Firebase
// firebaseConfig.js import { initializeApp } from 'firebase/app'; import { getAuth } from 'firebase/auth'; const firebaseConfig = { apiKey: "你的API_KEY", authDomain: "你的AUTH_DOMAIN", projectId: "你的PROJECT_ID", storageBucket: "你的STORAGE_BUCKET", messagingSenderId: "你的MESSAGING_SENDER_ID", appId: "你的APP_ID" }; const app = initializeApp(firebaseConfig); export const auth = getAuth(app);
谷歌登录组件
// GoogleSignInButton.js import React from 'react'; import { Button, View } from 'react-native'; import { makeRedirectUri, useAuthRequest } from 'expo-auth-session'; import { GoogleAuthProvider, signInWithCredential } from 'firebase/auth'; import { auth } from './firebaseConfig'; const discovery = { authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth', tokenEndpoint: 'https://oauth2.googleapis.com/token', }; export default function GoogleSignInButton() { const [request, response, promptAsync] = useAuthRequest( { clientId: '你的谷歌Web客户端ID', scopes: ['openid', 'profile', 'email'], redirectUri: makeRedirectUri(), }, discovery ); React.useEffect(() => { if (response?.type === 'success') { const { id_token } = response.params; const credential = GoogleAuthProvider.credential(id_token); signInWithCredential(auth, credential) .then(userCredential => console.log('登录成功:', userCredential.user)) .catch(err => console.error('登录失败:', err)); } }, [response]); return ( <View> <Button title="使用谷歌登录" onPress={() => promptAsync()} disabled={!request} /> </View> ); }
二、裸 React Native 项目(Bare Workflow)
使用维护中的 @react-native-google-signin/google-signin 包配合 Firebase 实现认证。
1. 安装依赖
npm install @react-native-google-signin/google-signin firebase # 或 yarn add @react-native-google-signin/google-signin firebase
2. 原生端配置
Android 端
- 在
android/app/build.gradle的dependencies块中添加:implementation 'com.google.android.gms:play-services-auth:20.7.0' - 在
android/app/src/main/AndroidManifest.xml的<application>标签内添加:<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> - 从 Firebase 下载
google-services.json,放入android/app目录,同时将谷歌云生成的 Android 客户端 ID(需匹配项目 SHA-1 指纹)配置到该文件中。
iOS 端
- 运行
npx pod-install安装依赖 Pods。 - 从 Firebase 下载
GoogleService-Info.plist,拖入 Xcode 项目(勾选「Copy items if needed」)。 - 在 Xcode 项目设置 →「Info」→「URL Types」中,添加一个 URL Type,其
URL Schemes填写谷歌云生成的 iOS 客户端 ID 的反向 ID(格式:com.googleusercontent.apps.xxxxxx)。
3. 代码实现
初始化 Firebase(同 Expo 项目的 firebaseConfig.js)
谷歌登录组件
// GoogleSignInButton.js import React from 'react'; import { Button, View } from 'react-native'; import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin'; import { GoogleAuthProvider, signInWithCredential } from 'firebase/auth'; import { auth } from './firebaseConfig'; // 配置 GoogleSignin GoogleSignin.configure({ webClientId: '你的谷歌Web客户端ID', iosClientId: '你的谷歌iOS客户端ID', // 仅iOS需要 }); export default function GoogleSignInButton() { const signIn = async () => { try { await GoogleSignin.hasPlayServices(); const userInfo = await GoogleSignin.signIn(); const credential = GoogleAuthProvider.credential(userInfo.idToken); const userCredential = await signInWithCredential(auth, credential); console.log('登录成功:', userCredential.user); } catch (error) { switch (error.code) { case statusCodes.SIGN_IN_CANCELLED: console.log('用户取消登录'); break; case statusCodes.IN_PROGRESS: console.log('登录流程正在进行'); break; case statusCodes.PLAY_SERVICES_NOT_AVAILABLE: console.log('设备未安装或未启用Google Play服务'); break; default: console.error('登录失败:', error); } } }; return ( <View> <Button title="使用谷歌登录" onPress={signIn} /> </View> ); }
内容的提问来源于stack exchange,提问作者tabba
相关产品推荐
相关产品推荐

