如何在React Native安卓端集成无Firebase的Google登录?
无需Firebase实现React Native Google认证指引
一、安装核心依赖
先安装官方维护的Google登录库:
npm install @react-native-google-signin/google-signin # 或使用yarn yarn add @react-native-google-signin/google-signin
二、Google Cloud Console配置
- 登录Google Cloud Console,创建或选择你的项目
- 搜索并启用「Google Identity API」和「Google People API」(获取用户基础信息需要)
- 进入「API和服务」→「凭据」,创建OAuth 2.0客户端ID:
- Android端:输入应用包名(如
com.yourappname),生成并填写SHA-1指纹(调试环境可通过keytool -list -v -keystore android/app/debug.keystore获取) - iOS端:输入应用Bundle ID,保存后获取iOS专属客户端ID
- Android端:输入应用包名(如
三、平台端配置
Android端
在android/app/src/main/AndroidManifest.xml的<application>标签内添加:
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
iOS端
在Info.plist中添加URL Scheme,格式为com.googleusercontent.apps.你的客户端ID:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>com.googleusercontent.apps.1234567890-abcdefghijklmnopqrstuvwxyz</string> </array> </dict> </array>
四、代码实现
1. 初始化配置
在App入口或单独的认证模块中完成初始化:
import { GoogleSignin } from '@react-native-google-signin/google-signin'; GoogleSignin.configure({ scopes: ['email', 'profile'], // 请求的用户权限 webClientId: '你的Web客户端ID', // 从Cloud Console获取的Web端ID offlineAccess: true, // 需要刷新令牌时设为true iosClientId: '你的iOS客户端ID', // iOS平台单独配置 });
2. 登录逻辑
const signInWithGoogle = async () => { try { // Android端检查Google Play服务是否可用 await GoogleSignin.hasPlayServices(); // 发起登录请求 const userInfo = await GoogleSignin.signIn(); // userInfo包含用户ID、姓名、邮箱、头像地址等信息 console.log('登录成功:', userInfo); // 将userInfo中的idToken发送到你的后端做身份验证 } catch (error) { console.error('登录失败:', error); } };
3. 获取当前登录用户
const getCurrentUser = async () => { try { const userInfo = await GoogleSignin.getCurrentUser(); console.log('当前用户:', userInfo); return userInfo; } catch (error) { console.error('获取用户信息失败:', error); } };
4. 登出操作
const signOut = async () => { try { await GoogleSignin.signOut(); console.log('登出成功'); } catch (error) { console.error('登出失败:', error); } };
五、后端验证(必做)
拿到用户返回的idToken后,需要发送到你的后端,调用Google官方验证接口https://oauth2.googleapis.com/tokeninfo?id_token=你的idToken,验证令牌合法性。验证通过后,再生成你的应用专属会话令牌返回给前端,完成完整的认证流程。
内容的提问来源于stack exchange,提问作者Abdul Rehman
相关产品推荐
相关产品推荐

