开发Google登录功能遭遇CORS跨域问题,请求技术支持
问题分析与解决方案
核心问题
你当前错误地用AJAX/fetch发起OAuth2授权请求,而OAuth2授权流程需要浏览器完整的页面跳转来维护会话上下文,AJAX请求无法处理第三方(Google)的重定向和登录会话,直接触发CORS错误。
解决方案
1. 前端代码修改
把fetch请求替换为页面跳转,让浏览器直接访问后端的Google授权入口:
const btnLoginGG = document.getElementById('btnGG') btnLoginGG.addEventListener('click', () => { window.location.href = 'http://localhost:8080/oauth2/authorization/google'; })
原有的/login/get-acc前端调用逻辑可暂时删除,授权成功后再通过正常请求获取用户信息。
2. 后端代码调整
- 确保Spring Security OAuth2已配置正确的回调地址(如
http://localhost:8080/login/oauth2/code/google),且Google开发者控制台同步配置了该回调URL。 - 调整用户信息接口,确保它在授权成功后可被正常访问:
@CrossOrigin(origins = "http://127.0.0.1:5500") @RestController @RequestMapping("/login") public class LoginController { @GetMapping("/get-account") public Object getAcc(Authentication authentication) { if (authentication instanceof OAuth2AuthenticationToken) { OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication; return token.getPrincipal().getAttributes().get("email"); } return "未授权"; } }
- 可选:全局配置CORS,避免单个接口注解的局限性:
@Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Collections.singletonList("http://127.0.0.1:5500")); config.setAllowedMethods(Collections.singletonList("*")); config.setAllowedHeaders(Collections.singletonList("*")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
3. 正确流程说明
- 用户点击登录按钮,浏览器跳转到后端的Google授权入口
- 后端重定向到Google登录授权页面,用户完成登录授权操作
- Google将授权码回调到后端配置的地址,后端用授权码换取AccessToken并获取用户信息
- 授权成功后,前端可通过AJAX请求
/login/get-account获取用户邮箱(此时已有登录会话,不会触发CORS问题)
原方案失效原因
- AJAX请求的重定向会被浏览器拦截,因为Google的响应没有CORS头,触发跨域错误
- 设置
no-cors后浏览器返回不透明响应,无法获取数据,且后端因无有效会话返回403未授权
内容的提问来源于stack exchange,提问作者Đoàn Trọng Thưởng PH 3 2 0 6 4
相关产品推荐
相关产品推荐

