最近在优化Spring Security权限分配时遇到了一个令人头疼的问题。项目中使用了基于角色的访问控制(RBAC),但在实际测试中发现权限控制并不如预期那样精确。
问题复现步骤:
- 配置了用户角色:ADMIN、USER、GUEST
- 使用@PreAuthorize注解设置权限:@PreAuthorize("hasRole('ADMIN')")
- 在Controller中添加测试接口:
@GetMapping("/admin-only")
@PreAuthorize("hasRole('ADMIN')")
public String adminOnly() {
return "只有管理员可见";
}
- 测试时发现USER角色用户也能访问该接口
排查过程: 经过调试发现,问题出在SecurityConfig配置上。默认的Spring Security配置中,如果未正确配置权限继承关系,会导致权限判断失效。需要明确指定角色前缀和权限匹配规则。
解决方案:
- 在SecurityConfig中显式配置:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123456"))
.roles("ADMIN", "USER");
}
- 修复权限注解:使用@PreAuthorize("hasRole('ROLE_ADMIN')")
- 配置全局安全策略:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().permitAll();
}
这个优化让权限控制更加精确,建议在项目初期就做好安全策略规划,避免后期出现权限漏洞。

讨论