Spring Security方法级角色权限失效导致用户越权访问接口
核心问题根因
- private方法导致方法权限注解完全失效:从启动日志可以看到,Spring Security的Web层过滤链是正常加载的,问题出在方法层面的拦截逻辑没有触发。Spring Security的方法级权限拦截基于AOP代理实现,无论JDK动态代理还是CGLIB代理,都无法拦截private修饰的方法。两个接口方法都是private,Spring MVC通过内部反射调用接口时,会绕过代理对象直接执行目标方法,方法上的
@PreAuthorize、@Secured注解完全不会被校验。 - hasRole表达式参数格式错误:Spring Security内置的
hasRole()方法会自动为传入参数拼接ROLE_前缀做权限匹配。代码中写的hasRole('ROLE_ONE')实际校验逻辑是检查用户是否拥有ROLE_ROLE_ONE权限,但通过.roles("ONE")给用户分配的实际权限是ROLE_ONE,哪怕注解能被拦截也匹配不上。 - 配置类写法过时且开关不全:继承
GlobalMethodSecurityConfiguration是Spring Security 3.x的旧写法,新版本中该类的存在容易引发Bean加载顺序异常,导致方法权限拦截器无法正常织入代理链。同时@EnableGlobalMethodSecurity注解只开启了prePostEnabled,没有开启securedEnabled开关,就算换用@Secured注解也不会生效。 - 缺少基础HTTP安全规则配置:当前配置没有自定义HTTP拦截逻辑,只要通过了基础用户名密码认证,没有额外的权限校验逻辑兜底,自然两个用户都能访问所有接口。
修正方案
- 将两个控制器的接口方法从
private改为public,让AOP代理能正常拦截方法调用。 - 修正权限表达式写法:
- 使用
hasRole()时直接传入角色名,不要手动加ROLE_前缀,比如@PreAuthorize("hasRole('ONE')")、@PreAuthorize("hasRole('TWO')") - 如果要保留带
ROLE_前缀的写法,换用不会自动拼接前缀的hasAuthority(),比如@PreAuthorize("hasAuthority('ROLE_ONE')")
- 使用
- 调整安全配置类,去掉过时的继承关系,补全必要的配置开关和HTTP拦截规则:
@Configuration @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfig { @Bean public AuthenticationManager configureGlobal(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); return auth .inMemoryAuthentication() .withUser("user").password(encoder.encode("password")).roles("ONE") .and() .withUser("user2").password(encoder.encode("password2")).roles("TWO") .and() .eraseCredentials(true) .build(); } // 配置基础HTTP安全规则,确保所有接口需认证后才能访问 @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); return http.build(); } } - 修复后验证逻辑:
- 使用user账号(密码
password)请求时,仅能访问/one接口,访问/two会返回403无权限响应 - 使用user2账号(密码
password2)请求时,仅能访问/two接口,访问/one会返回403无权限响应
- 使用user账号(密码
内容的提问来源于stack exchange,提问作者HastilyMadeAccount12345
相关产品推荐
相关产品推荐

