In Spring Security 6 and Spring Boot 3, the method to include RoleHierarchy in the expressionHandler is as follows:
@Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy("ROLE_SUPERADMIN > ROLE_ADMIN\nROLE_ADMIN > ROLE_USER");
return 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.
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
Asked: 2023-06-06 13:02:35 +0000
Seen: 15 times
Last updated: Jun 06 '23