You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Expo SDK 49中不使用@react-native-google-signin实现Firebase谷歌登录?

Expo SDK 49 下用 Firebase GoogleAuthProvider 实现登录的可行方案

核心配置与步骤

1. 正确配置 Google Cloud OAuth 客户端

  • 登录 Google Cloud 控制台,进入你的项目,打开「API和服务」→「凭据」
  • 创建三类客户端ID:
    • Web应用:作为expoClientId,需添加授权重定向URI:https://auth.expo.io/@你的Expo用户名/你的项目slug(slug可在app.json中查看)
    • iOS应用:Bundle ID填host.exp.exponent(Expo Go的默认Bundle ID),生成的ID作为iosClientId
    • Android应用:SHA-1证书指纹填Expo官方提供的BB:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75,生成的ID作为androidClientId
  • 确保OAuth同意屏幕已配置:选择「外部」类型,填写基础信息,添加测试用户(测试状态下仅测试用户可登录)

2. Firebase 配置

  • 无需在app.json中配置googleServicesFile,直接使用Firebase Web SDK的配置初始化:
    从Firebase控制台获取Web应用的配置参数(apiKey、authDomain等),在代码中初始化Firebase Auth实例

3. 修正后的代码实现

先安装依赖:

expo install expo-auth-session expo-random firebase

完整代码示例:

import React, { useEffect } from 'react';
import { View, Button } from 'react-native';
import * as Google from 'expo-auth-session/providers/google';
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithCredential, GoogleAuthProvider } from 'firebase/auth';

// Firebase Web配置(替换为你的项目参数)
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export default function GoogleSignInScreen() {
  const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: "你的Google Web客户端ID",
    iosClientId: "你的Google iOS客户端ID",
    androidClientId: "你的Google Android客户端ID",
  });

  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(error => {
          console.error('登录失败:', error.message);
        });
    }
  }, [response]);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Button 
        title="谷歌登录" 
        onPress={() => promptAsync()} 
        disabled={!request} 
      />
    </View>
  );
}

4. Error 400: invalid_request 排查要点

  • 检查所有客户端ID是否属于同一个Google Cloud项目,且Firebase认证已启用Google登录
  • 确认Web客户端ID的重定向URI完全匹配Expo的格式,无拼写错误
  • 检查OAuth同意屏幕的测试用户列表是否包含当前登录的Google账号
  • 确保expoClientId、iosClientId、androidClientId参数未填混

内容的提问来源于stack exchange,提问作者Sour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:46:01