Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In Spring Security 6 and Spring Boot 3, the method to include RoleHierarchy in the expressionHandler is as follows:

  1. Add the RoleHierarchy bean to the application context:
@Bean
public RoleHierarchy roleHierarchy() {
    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    roleHierarchy.setHierarchy("ROLE_SUPERADMIN > ROLE_ADMIN\nROLE_ADMIN > ROLE_USER");
    return roleHierarchy;
}
  1. Configure the expressionHandler to use the RoleHierarchy:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RoleHierarchy roleHierarchy;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .csrf().disable()
                .expressionHandler(expressionHandler());
    }

    private DefaultWebSecurityExpressionHandler expressionHandler() {
        DefaultWebSecurityExpressionHandler expressionHandler = new DefaultWebSecurityExpressionHandler();
        expressionHandler.setRoleHierarchy(roleHierarchy);
        return expressionHandler;
    }
}

In this example, the RoleHierarchy is defined with two roles: ROLESUPERADMIN is the highest role, followed by ROLEADMIN, and then ROLEUSER. The expressionHandler is then configured to use the RoleHierarchy. When the hasRole() method is used in a security constraint, the specified role is checked along with any roles in the hierarchy above it. For example, a user with the role ROLESUPERADMIN would have access to any resource that requires the roles ROLESUPERADMIN, ROLEADMIN, or ROLE_USER.