我试图在我的Spring Boot应用程序中设置分层角色,但没有成功。我已经完成了互联网上不同地方所说的一切。但是我没有一个能够解决这个问题。Spring Boot + Spring Security +分层角色
这是我的SecurityConfig类的代码。当我在ROLE_ADMIN用户的应用程序中登录时,它应该能够从'/ users'中检索数据,但目前我收到拒绝访问异常。如果用户具有ROLE_USER凭证,则它工作正常。 任何人都可以帮我弄清楚什么是失败? 在此先感谢。
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SigpaUserDetailsService userDetailsService;
@Bean
public RoleHierarchyImpl roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");
return roleHierarchy;
}
@Bean
public RoleHierarchyVoter roleVoter() {
return new RoleHierarchyVoter(roleHierarchy());
}
@Bean
public DefaultWebSecurityExpressionHandler expressionHandler(){
DefaultWebSecurityExpressionHandler expressionHandler = new DefaultWebSecurityExpressionHandler();
expressionHandler.setRoleHierarchy(roleHierarchy());
return expressionHandler;
}
@Bean
@SuppressWarnings(value = { "rawtypes" })
public AffirmativeBased accessDecisionManager() {
List<AccessDecisionVoter> decisionVoters = new ArrayList<AccessDecisionVoter>();
WebExpressionVoter webExpressionVoter = new WebExpressionVoter();
webExpressionVoter.setExpressionHandler(expressionHandler());
decisionVoters.add(webExpressionVoter);
decisionVoters.add(roleVoter());
return new AffirmativeBased(decisionVoters);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.accessDecisionManager(accessDecisionManager())
.expressionHandler(expressionHandler())
.antMatchers("https://stackoverflow.com/users/**")
.access("hasRole('ROLE_USER')")
.anyRequest().authenticated();
http
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder registry)
throws Exception {
registry.userDetailsService(userDetailsService);
}
}
更新:这里是你的建议更新的代码,但仍无法工作的。
它不这样工作。我仍然收到相同的访问拒绝异常 – Mario 2014-10-30 21:53:04
@Mario尝试我的更新。 – holmis83 2014-10-31 08:05:37
我昨天已经这么做了......我不知道为什么不工作,因为我已经尽一切努力没有取得任何成功。 – Mario 2014-10-31 12:04:57