Spring Boot分离OAuth2认证服务后登录跳转根路径无法访问其他端点
问题核心原因
两个异常均由配置不匹配导致:
- 登录后跳转根路径:你配置了
SessionCreationPolicy.STATELESS无状态会话,OAuth2授权码流程依赖Session存储登录前的原始请求地址,无状态模式下该缓存丢失,登录后只能跳转到默认根路径。 - 权限校验失败:OAuth2登录的用户信息默认仅携带SCOPE类权限,没有映射你业务需要的
ROLE_MYUSER/ROLE_MYADMIN角色,就算登录成功也无法通过接口的角色校验。
具体修改步骤
1. 调整客户端会话策略(解决跳转问题)
删除WebSecurityConfig中无状态会话的配置,或改为按需创建会话:
// 删除这行配置 // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
若确实需要弱会话控制,可改为:
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
修改后Spring Security会自动缓存登录前的请求地址,登录成功后自动跳转回原始访问的端点。
2. 授权服务器返回用户角色信息
修改授权服务器UserController的/user/me接口,返回完整的用户权限信息:
@RestController public class UserController { @GetMapping("/user/me") public Map<String, Object> user(Principal principal) { Authentication auth = (Authentication) principal; Map<String, Object> userInfo = new HashMap<>(); userInfo.put("name", principal.getName()); // 把用户角色加入返回值 userInfo.put("authorities", auth.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList())); return userInfo; } }
同时确认授权服务器的用户配置中已经给相应用户分配了ROLE_MYUSER/ROLE_MYADMIN角色:
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("myuser") .password(passwordEncoder().encode("你的用户密码")) .roles("MYUSER") .and() .withUser("myadmin") .password(passwordEncoder().encode("你的管理员密码")) .roles("MYUSER", "MYADMIN"); }
3. 客户端映射OAuth2用户权限
在客户端WebSecurityConfig中添加自定义OAuth2用户服务,把授权服务器返回的角色映射到本地权限体系:
@Bean public OAuth2UserService<OAuth2UserRequest, OAuth2User> oAuth2UserService() { DefaultOAuth2UserService defaultService = new DefaultOAuth2UserService(); return userRequest -> { OAuth2User originalUser = defaultService.loadUser(userRequest); // 读取授权服务器返回的权限列表 List<String> authorityList = originalUser.getAttribute("authorities"); Set<GrantedAuthority> grantedAuthorities = Optional.ofNullable(authorityList) .orElse(Collections.emptyList()) .stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); // 保留默认的SCOPE类权限 grantedAuthorities.addAll(originalUser.getAuthorities()); // 构造带业务角色的用户信息 return new DefaultOAuth2User(grantedAuthorities, originalUser.getAttributes(), "name"); }; }
然后在HttpSecurity配置中关联该服务:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/abc/**").hasRole("MYUSER") // 保留你原有的其他权限规则 .anyRequest().authenticated() .and() .oauth2Login() // 关联自定义的用户权限转换服务 .userInfoEndpoint() .userService(oAuth2UserService()); }
4. 清理冗余配置
如果你已经完全切换到OAuth2认证,不需要再保留原Basic Auth的UserDetailsService Bean,可以直接删除,避免权限逻辑混淆。如果需要保留Basic Auth和OAuth2共存,重新加上.httpBasic()配置即可。
内容的提问来源于stack exchange,提问作者neblaz
相关产品推荐
相关产品推荐

