SpringBoot集成Google OAuth2时@RequestMapping失效及认证配置问题
问题1:@RequestMapping不生效解决方案
根本原因有两个:
- 你在
application.yml中把Google授权后的重定向地址配置为了/welcome.html,而Spring OAuth2客户端默认并不会处理这个路径的授权回调逻辑,Google返回的授权码code没有被兑换成access_token,也就没有建立有效的用户认证会话,后续你访问所有接口都会被拦截跳转到登录页,自然触发不到Controller。 - 如果你的
resources/static目录下存在同名的welcome.html静态文件,Spring MVC会优先返回静态资源,不会进入Controller方法。
修改操作:
- 把
application.yml中的redirect-uri改为Spring OAuth2客户端默认的回调地址:http://localhost:8080/security/login/oauth2/code/google - 移除静态资源目录下的
welcome.html文件,或者把Controller的请求路径改为不与静态资源重名的路径,比如/api/welcome
问题2:获取AccessToken实现方案
Spring Security的oauth2Login组件已经自动封装了授权码换AccessToken的POST请求逻辑,不需要你手动发起调用,授权成功后可以直接从上下文获取令牌:
import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AppController { @GetMapping("/welcome") public String getHi(@RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient authorizedClient, @AuthenticationPrincipal OAuth2User oauth2User) { // 直接拿到AccessToken String accessToken = authorizedClient.getAccessToken().getTokenValue(); System.out.println("AccessToken: " + accessToken); // 拿到用户信息 System.out.println("用户邮箱: " + oauth2User.getAttribute("email")); return "Hi"; } }
如果需要自定义授权成功后的跳转逻辑,可以在SecurityConfig中配置登录成功处理器:
.oauth2Login() .successHandler((request, response, authentication) -> { // 授权成功后跳转到/welcome接口 response.sendRedirect("/security/welcome"); })
问题3:仅特定URL触发OAuth2重定向解决方案
修改SecurityConfig中的授权规则,不要使用anyRequest().authenticated(),改为只给需要保护的路径配置认证要求,其余路径放行:
@Override protected void configure(HttpSecurity http) throws Exception { http .cors().disable() .csrf().disable() .authorizeRequests() // 只有/api开头的路径需要认证,才会触发OAuth2重定向 .antMatchers("/api/**").authenticated() // 其余所有路径直接放行 .anyRequest().permitAll() .and() .oauth2Login() // 登录成功跳转到/welcome .successHandler((request, response, authentication) -> { response.sendRedirect("/security/welcome"); }); }
修改后只有访问/api前缀的路径时才会触发Google登录重定向,直接访问上下文根/security不会触发认证。
内容的提问来源于stack exchange,提问作者user16334809
相关产品推荐
相关产品推荐

