I\'m trying to setup hierarchical roles in my Spring Boot app without success. I\'ve done all that\'s been said in different places in the Internet. But with none of them ha
To Enable Method Level Security( ie @EnableGlobalMethodSecurity(prePostEnabled = true)) along with supporting Hierarchical-role on WebSecurityConfigurerAdapter.
1.Just need to seperate the RoleHierarchy on any other class annotated with @Bean
2.Inject it using @Autowired on WebSecurityConfigurerAdapter.
It is working flawlessly on my projects.
Please have a look into my code.
WeSecurityConfig.class
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RoleHierarchy roleHierarchy;
private SecurityExpressionHandler webExpressionHandler() {
DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy);
return defaultWebSecurityExpressionHandler;
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
web.ignoring().antMatchers("/static/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.expressionHandler(webExpressionHandler())
.antMatchers("/static/**","/bower_components/**","/").permitAll()
.antMatchers("/user/login","/user/login?error").anonymous()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/user/login").passwordParameter("password").usernameParameter("username")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout().logoutUrl("/user/logout")
.logoutSuccessUrl("/user/login?logout")
.and().csrf();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
public DaoAuthenticationProvider daoAuthenticationProvider(){
final DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userDetailService);
auth.setPasswordEncoder(passwordEncoder);
return auth;
}
}
BeanConfiguration.class
@Configuration
public class BeanConfiguration {
@Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
/* tricks lies here */
roleHierarchy.setHierarchy("ROLE_SUPREME > ROLE_ADMIN ROLE_ADMIN > ROLE_OPERATOR ROLE_OPERATOR > ROLE_GUEST");
return roleHierarchy;
}
}
Hope It helps you.