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

Vue3+NestJS集成Google OAuth2遇redirect_uri_mismatch错误求助

解决Vue3+NestJS集成Google Auth时的redirect_uri_mismatch错误

你遇到的问题核心是前端发起Google授权请求时的redirect_uri和Google Cloud Console配置的不一致,而非后端的callbackURL配置——因为你当前的流程是前端先获取授权码,再传给后端验证,这时候Google校验的是前端授权请求里的redirect_uri,不是后端的回调地址。

1. 定位真实的redirect_uri

打开浏览器开发者工具(F12),切换到网络标签,触发Google登录流程,找到向https://accounts.google.com/o/oauth2/v2/auth的请求,查看请求参数里的redirect_uri值。这个值才是Google真正校验的地址,必须和你在Google Console里配置的完全一致。

2. 修正Google Console配置

登录Google Cloud Console,找到你的OAuth 2.0客户端ID,在已获授权的重定向URI列表中:

  • 添加刚才查到的前端redirect_uri(比如http://localhost:3000/google-callback,具体看你的前端回调路径)
  • 确保地址完全匹配:http/https不能混、localhost和127.0.0.1是不同域名、端口不能错、尾部斜杠要一致
  • 注意:配置修改后可能需要等待1-5分钟才会生效,别刚改完就测试

3. 调整前端授权库配置

如果你用的是vue-google-oauth2这类前端OAuth库,初始化时必须明确指定redirect_uri,和上面的地址保持一致。示例:

// 前端Google OAuth初始化示例
import GAuth from 'vue-google-oauth2'

const gauthOption = {
  clientId: '你的Google Client ID',
  scope: 'profile email',
  redirectUri: 'http://localhost:3000/google-callback' // 必须和Console配置、授权请求里的一致
}

app.use(GAuth, gauthOption)

4. 修正后端逻辑(关键)

你当前用的Passport GoogleStrategy是为服务器端跳转授权设计的(后端直接重定向到Google登录),但你的流程是前端拿code传给后端,这时候应该改用手动用授权码交换Token的方式,而非依赖Passport的Strategy:

安装googleapis依赖

npm install googleapis

在NestJS的Auth服务中实现Token交换

import { Injectable } from '@nestjs/common';
import { google } from 'googleapis';

@Injectable()
export class AuthService {
  private oauth2Client;

  constructor() {
    this.oauth2Client = new google.auth.OAuth2(
      process.env.GOOGLE_CLIENT_ID,
      process.env.GOOGLE_CLIENT_SECRET,
      'http://localhost:3000/google-callback' // 必须和前端授权时的redirect_uri一致
    );
  }

  async googleLogin(code: string) {
    // 用授权码交换Token
    const { tokens } = await this.oauth2Client.getToken(code);
    this.oauth2Client.setCredentials(tokens);

    // 获取Google用户信息
    const userInfo = await google.oauth2('v2').userinfo.get({
      auth: this.oauth2Client,
    });

    // 后续逻辑:创建/查询本地用户、生成JWT等
    return {
      user: userInfo.data,
      accessToken: '你的JWT Token',
    };
  }
}

调整后端控制器

import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('google/callback')
  async googleCallback(@Body('code') code: string) {
    return this.authService.googleLogin(code);
  }
}

常见排查点

  • 确认Google Console选对了项目:有时候会误操作到其他项目,导致配置的URI不在当前使用的Client ID下
  • 清除浏览器缓存和Cookie:旧的授权会话可能残留错误的redirect_uri参数
  • 检查CORS配置:后端要允许http://localhost:3000的跨域请求(虽然和redirect_uri错误无关,但会导致前端传code失败)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:23:12