Ask Your Question
4

Using the expressionHandler, what is the method to include RoleHierarchy in Spring Security 6 and Spring Boot 3?

asked 2023-06-06 13:02:35 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-06 13:09:02 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-06 13:02:35 +0000

Seen: 15 times

Last updated: Jun 06 '23