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

Fastify+NestJS下Google Auth的redirect_uri_mismatch错误解决咨询

解决Google OAuth 'redirect_uri_mismatch' 错误

以下是针对你的场景的具体排查和解决步骤:

1. 统一前后端的redirect_uri配置

OAuth 2.0授权码流程要求:前端发起授权请求时的redirect_uri,必须和后端换取令牌时使用的redirect_uri完全一致,同时也要和Google云平台配置的URI匹配。

你的后端代码中指定了redirect_uri: "http://localhost:4000/api/auth/google/redirect",但前端useGoogleLogin未显式配置该参数,此时@react-oauth/google会默认使用当前前端页面的Origin(比如http://localhost:3000)作为redirect_uri,这就导致了不匹配。

修改前端代码,显式添加redirect_uri参数:

const googleLogin = useGoogleLogin({
    flow: "auth-code",
    redirect_uri: "http://localhost:4000/api/auth/google/redirect", // 与后端、GCP配置保持一致
    onSuccess: async (codeResponse) => {
      console.log(codeResponse);
      const tokens = await axios.post("http://localhost:4000/api/auth/google", {
        code: codeResponse.code,
      });

      console.log(tokens);
    },
    onError: (errorResponse) => console.log(errorResponse),
  });

2. 验证Google云平台的配置细节

  • 确认你在GCP OAuth 2.0客户端ID配置中,添加的redirect_uri与上述值完全一致,包括协议(http/https)、端口、路径,不能有多余的斜杠或大小写差异。
  • 确保你创建的是Web应用类型的客户端ID,而非iOS/Android等其他类型,不同类型的客户端对redirect_uri的要求不同。

3. 检查配置生效情况

GCP的OAuth配置修改后,可能需要3-5分钟才能全局生效,修改后等待片刻再测试。同时可以清除浏览器缓存,或使用无痕模式测试,避免旧的授权会话缓存干扰。

4. 确认本地环境的URI合法性

本地开发环境中,localhost是Google允许使用http协议的特例,无需切换到https,但要确保前后端的redirect_uri都使用http协议(如果你的前端/后端是https则统一用https)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:57:29