使用Google登录时遭遇redirect_uri_mismatch错误求助
Google OAuth授权码兑换ID Token时出现redirect_uri_mismatch错误
错误详情
调用Google Token接口时返回400错误:
400 Bad Request POST https://oauth2.googleapis.com/token { "error": "redirect_uri_mismatch", "error_description": "Bad Request" }
注意:前端可正常获取授权码,仅后端兑换授权码时触发该错误。
已通过搜索官方文档、StackOverflow及AI工具排查,问题仍未解决。
技术环境与代码
React前端(@react-oauth/google: ^0.12.1)
const login = useGoogleLogin({ flow: 'auth-code', onSuccess: async (response) => { try { var data = { code: response.code }; const session = await post('api/v1/sessions', data); } catch (error) { console.log(error); } }, onError: error => console.log(error), redirect_uri: 'http://localhost:5173/login' }); return ( <div className="p-4"> <div className="space-y-6 text-left"> <Button label="Sign with Google" onClick={() => login()} type="button" /> </div> </div> );
Spring Boot后端(3.2.2 + Java 21,google-api-client-servlet: 2.4.0)
public GoogleIdToken getIdToken(ClientSecrets secrets, String authorizationCode) { try { var response = new GoogleAuthorizationCodeTokenRequest( new NetHttpTransport(), GsonFactory.getDefaultInstance(), secrets.getDetails().getTokenUri(), secrets.getDetails().getClientId(), secrets.getDetails().getClientSecret(), authorizationCode, "http://localhost:5173/login") // redirectUri .execute(); return response.parseIdToken(); } catch (Exception e) { throw e; } }
当前配置
- 代码中配置的redirectUri:
http://localhost:5173/login - Google Cloud控制台配置:已在OAuth 2.0客户端ID中添加对应重定向URI(需确保与代码中的值完全一致,包括协议、端口、路径,无多余斜杠或大小写差异)
排查方向
- 严格匹配重定向URI:确认Google控制台中配置的重定向URI与后端代码传入的
http://localhost:5173/login完全一致,重点检查:- 协议(http/https)是否一致
- 端口号是否正确(5173)
- 路径是否完全匹配(末尾是否多了斜杠,或拼写错误)
- 大小写是否一致(URI区分大小写)
- 客户端ID一致性:确保前端获取授权码和后端兑换Token使用的是同一个OAuth 2.0客户端ID,避免误使用其他类型的客户端(如Android/iOS客户端)
- 授权码绑定规则:授权码生成时绑定的redirect_uri必须与兑换时的完全相同,前端获取授权码时配置的redirect_uri已确认正确,需保证后端传入的参数与之完全一致
- 清除缓存:清理浏览器缓存及Google账号的授权会话,避免旧的授权信息干扰
- 检查Token接口地址:确认后端调用的Token接口地址为
https://oauth2.googleapis.com/token,无拼写错误
内容的提问来源于stack exchange,提问作者James Schmidt
相关产品推荐
相关产品推荐

