如何配置Spring Boot Security实现User/Admin角色分属不同首页及独立控制器
解决方案
1. 修复角色权限匹配规则
Spring Security 中hasRole()方法会自动给传入的角色名拼接ROLE_前缀,即你配置的.antMatchers("/admin/**").hasRole("ADMIN")实际校验的是用户是否持有ROLE_ADMIN权限,若你自定义UserDetailsService赋权时没有加该前缀,会直接触发权限校验失败,请求被拦截,不会进入对应的Controller。
推荐直接修改Security配置,改用无自动前缀的hasAuthority()方法匹配:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasAuthority("ADMIN") .antMatchers("/user/**").hasAuthority("USER") .antMatchers("/**").permitAll() .and().formLogin() .loginPage("/") .loginProcessingUrl("/doLogin") .defaultSuccessUrl("/successHandler") .and().csrf().disable(); }
如果不想改配置,也可以在给用户赋权时统一加上ROLE_前缀,示例:
// UserDetailsServiceImpl中返回权限时的写法 List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"));
2. 确认模板路径配置正确
检查Thymeleaf模板存放路径是否符合要求:
- Admin首页模板路径:
resources/templates/admin/home.html - User首页模板路径:
resources/templates/user/home.html
如果你的Spring Boot修改过默认模板前缀spring.thymeleaf.prefix,需要对应调整模板存放位置。
3. 可选排查方案
如果以上修改后仍未生效,可以在application.properties中开启Security debug日志,精准定位拦截原因:
logging.level.org.springframework.security=DEBUG
启动项目登录后查看控制台日志,即可看到权限校验的具体失败原因。
内容的提问来源于stack exchange,提问作者Ahmed
相关产品推荐
相关产品推荐

