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

React Native Expo中Google登录遇Error 400: redirect_uri_mismatch问题

解决Expo React Native Google登录的redirect_uri_mismatch错误

以下是几个关键排查和解决步骤:

  • 核对redirect_uri的格式与平台匹配
    Expo的Google登录redirect_uri有固定格式,不能随意填写:

    • 本地用Expo Go开发时,格式是 exp://localhost:19000/--/expo-auth-session,也可以用设备IP替换localhost,比如exp://192.168.1.100:19000/--/expo-auth-session
    • 如果是自定义开发构建(Custom Development Build),Android的redirect_uri为 com.your-app-package:/oauth2redirect/google,iOS的为 com.your-app-bundle-id:/oauth2redirect/google
      务必保证代码里的redirectUri和Google控制台配置的完全一致,包括大小写、斜杠等细节。
  • 检查Google控制台的客户端配置

    • 不同平台对应不同的客户端类型:Expo Go用Web应用客户端ID,自定义构建用Android/iOS客户端ID
    • 每个客户端的redirect_uri要单独配置,不能把Android的地址加到Web客户端里,反之亦然
  • 清除缓存并重启服务

    • 长按Expo Go里的项目图标,选择“清除缓存”
    • 终端里停止Metro服务(Ctrl+C),重新运行npx expo start
    • Google的配置可能需要几分钟生效,修改后等一会儿再测试
  • 让Expo自动生成redirectUri
    代码里可以不用手动指定redirectUri,Google.useAuthRequest会根据当前环境自动生成正确地址。去掉代码里的redirectUri参数,运行后查看控制台输出的request.redirectUri,把这个地址复制到Google控制台添加即可。

  • 确认实际请求的redirect_uri
    查看你代码里console.log("Auth Request:", request);的输出,找到request对象里的redirectUri字段,这个才是实际发给Google的地址,把它复制到Google控制台里配置,确保完全一致。

修改后的示例代码:

import React, { createContext, useContext } from 'react';
import * as Google from 'expo-auth-session/providers/google';
import * as WebBrowser from 'expo-web-browser';

WebBrowser.maybeCompleteAuthSession();

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
  
  // 移除手动指定的redirectUri,由Expo自动生成
  const [request, response, promptAsync] = Google.useAuthRequest({
    androidClientId: "你的Android客户端ID",
    iosClientId: "你的iOS客户端ID",
    expoClientId: "你的Expo客户端ID",
  });

  const signInWithGoogle = async () => {
    try {
      // 打印实际请求的redirectUri,方便核对
      console.log("实际请求的redirectUri:", request?.redirectUri);
      await promptAsync();

      if (response?.type === "success") {
        // 登录成功后可获取用户信息,示例如下
        const { authentication } = response;
        // const userInfoRes = await fetch('https://www.googleapis.com/userinfo/v2/me', {
        //   headers: { Authorization: `Bearer ${authentication.accessToken}` },
        // });
        // const userInfo = await userInfoRes.json();
        // console.log("用户信息:", userInfo);
      }

    } catch (error) {
      console.error("Google登录失败:", error);
    }
  };

  return (
    <AuthContext.Provider 
        value={{
            user: null,
            signInWithGoogle: signInWithGoogle,
        }}
    >
        {children}
    </AuthContext.Provider>
  );
};

export default function useAuth() {
  return useContext(AuthContext);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:44:58