Spring Boot集成Google OAuth2登录访问Calendar API遇授权端点404问题求助
问题原因
你遇到的404错误核心原因是OAuth2授权回调路径不匹配:Spring Security OAuth2客户端默认的回调路径前缀是/login/oauth2/code/,但你在Google Cloud平台配置的回调地址是/authorize/oauth2/code/google,同时你自定义了登录页后没有显式配置Spring Security的重定向端点匹配路径,导致该回调请求没有被OAuth2过滤器处理,直接被当成普通接口返回404。
解决方案
1. 修复回调路径404问题
两种方案二选一即可:
- 方案一:修改Google Cloud控制台的OAuth 2.0授权重定向URI为默认值
http://localhost:8080/login/oauth2/code/google,不需要修改Spring代码配置 - 方案二:在Spring安全配置中显式指定重定向端点和你当前Google配置的路径一致,修改
configure方法代码如下:
@Override protected void configure(HttpSecurity http) throws Exception { http.sessionManagement() // 保留原有表单登录配置 .and() .oauth2Login().loginPage("/signin") // 新增重定向端点配置,匹配你当前使用的回调路径 .redirectionEndpoint() .baseUri("/authorize/oauth2/code/*") .and() .authorizationEndpoint() .and() .userInfoEndpoint() .oidcUserService(oAuth2UserDetailsService); }
2. 顺带解决refresh_token为空、需要反复授权的问题
你代码中注释的refresh_token为空是因为Google默认仅首次授权返回refresh_token,需要在授权请求中添加access_type=offline参数,修改授权端点配置即可:
// 先注入ClientRegistrationRepository @Autowired private ClientRegistrationRepository clientRegistrationRepository; @Override protected void configure(HttpSecurity http) throws Exception { http.sessionManagement() // 保留原有表单登录配置 .and() .oauth2Login().loginPage("/signin") .redirectionEndpoint() .baseUri("/authorize/oauth2/code/*") .and() .authorizationEndpoint() // 自定义授权请求,添加Google要求的离线访问参数 .authorizationRequestResolver(new OAuth2AuthorizationRequestResolver() { private final OAuth2AuthorizationRequestResolver defaultResolver = new DefaultOAuth2AuthorizationRequestResolver( clientRegistrationRepository, "/oauth2/authorization"); @Override public OAuth2AuthorizationRequest resolve(HttpServletRequest request) { OAuth2AuthorizationRequest req = defaultResolver.resolve(request); return customizeGoogleAuthRequest(req); } @Override public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId) { OAuth2AuthorizationRequest req = defaultResolver.resolve(request, clientRegistrationId); return customizeGoogleAuthRequest(req); } private OAuth2AuthorizationRequest customizeGoogleAuthRequest(OAuth2AuthorizationRequest req) { if (req == null || !"google".equals(req.getClientRegistrationId())) { return req; } Map<String, Object> additionalParams = new HashMap<>(req.getAdditionalParameters()); // 配置离线访问,获取refresh_token additionalParams.put("access_type", "offline"); // 可选配置:强制每次授权都弹出确认页,确保返回refresh_token additionalParams.put("prompt", "consent"); return OAuth2AuthorizationRequest.from(req) .additionalParameters(additionalParams) .build(); } }) .and() .userInfoEndpoint() .oidcUserService(oAuth2UserDetailsService); }
配置完成后,Spring Security会自动处理access_token过期刷新,不需要用户反复授权。
3. 验证配置
重启项目,清除浏览器缓存以及Google账号的历史授权记录,重新发起授权测试即可。
内容的提问来源于stack exchange,提问作者Joaquín L. Robles
相关产品推荐
相关产品推荐

