Google身份验证Code Model出现redirect_uri_mismatch错误求助
Google OAuth授权码兑换令牌时出现redirect_uri_mismatch错误排查与解决
问题背景
技术栈:后端NestJS + 前端React,搭建Google OAuth Code模式以获取用户日历数据,卡在授权码兑换刷新令牌/访问令牌步骤,调用oauth2Client.getToken(code)时触发redirect_uri_mismatch错误。
已完成流程:
- 用户点击前端按钮,通过
google.accounts.oauth2.initCodeClient配置/calendar权限、ux_mode: popup - 弹出Google授权窗口,用户完成验证后,前端收到授权码
- 前端将授权码POST至后端接口
localhost:4000/auth/google-test
相关代码:
后端OAuth2Client初始化
export const oauth2Client = new google.auth.OAuth2( process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET, 'http://localhost:4000/' // 此处存疑 );
后端控制器路由
@Post('google-test') public async googleTest(@Body() bodyReceived: any): Promise<any> { let { code } = bodyReceived let { tokens } = await oauth2Client.getToken(code) oauth2Client.setCredentials(tokens); console.log('Tokens: ' + tokens); return }
GCP已配置的授权重定向URI:
- http://localhost:3000/home
- http://localhost:4000/auth/google-test
- http://localhost:4000
问题原因
redirect_uri_mismatch错误的核心是三个环节的redirect_uri必须完全一致:
- 前端发起授权请求时配置的
redirect_uri - 后端兑换授权码时使用的
redirect_uri - GCP控制台中已授权的重定向URI
当前问题出在:
- 前端
initCodeClient未显式配置redirect_uri,导致Google默认使用的地址与后端配置不一致 - 后端OAuth2Client初始化的
redirect_uri为http://localhost:4000/,与前端实际使用的redirect_uri(或GCP中配置的前端地址)不匹配
解决方案
1. 前端显式配置正确的redirect_uri
在initCodeClient中添加redirect_uri参数,值为GCP已授权的前端页面地址(比如http://localhost:3000/home):
const codeClient = google.accounts.oauth2.initCodeClient({ client_id: '你的Google Client ID', scope: 'https://www.googleapis.com/auth/calendar', ux_mode: 'popup', redirect_uri: 'http://localhost:3000/home', // 必须与GCP配置完全一致 callback: (response) => { // 将授权码POST至后端 fetch('http://localhost:4000/auth/google-test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: response.code }) }); } });
2. 后端同步redirect_uri配置
两种方式二选一:
方式一:初始化OAuth2Client时指定正确的redirect_uri
将后端OAuth2Client的redirect_uri改为与前端一致的地址:
export const oauth2Client = new google.auth.OAuth2( process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET, 'http://localhost:3000/home' // 和前端redirect_uri完全匹配 );
方式二:调用getToken时手动指定redirect_uri
在兑换授权码时,显式传入与前端一致的redirect_uri:
@Post('google-test') public async googleTest(@Body() bodyReceived: any): Promise<any> { let { code } = bodyReceived // 手动指定和前端一致的redirect_uri const { tokens } = await oauth2Client.getToken({ code, redirect_uri: 'http://localhost:3000/home' }); oauth2Client.setCredentials(tokens); console.log('Tokens:', tokens); return tokens; }
3. 校验GCP配置的URI一致性
确保GCP控制台中的授权重定向URI包含你使用的地址,且完全匹配(注意末尾斜杠、端口号、路径都不能错)。
额外注意事项
- 授权码只能使用一次,重复调用会报错,测试时需重新获取新的授权码
- 确认GCP凭据类型为「Web应用」,而非桌面应用或其他类型
- 检查Client ID和Client Secret前后端配置是否一致,无拼写错误
内容的提问来源于stack exchange,提问作者Allen Y
相关产品推荐
相关产品推荐

