Back to Research
Authorization
RBAC
Spring Security
Spring Boot
Java
RoleHierarchy

Role hierarchy in Spring Security: ADMIN inherits from MANAGER

How to make ADMIN inherit everything from MANAGER with RoleHierarchy in Spring Boot, in URL rules and @PreAuthorize, and when not to use it.

6 min read

Most systems have a ladder of roles: an admin can do everything a manager can, and so on. Without telling Spring Security, every rule must list every role above it. RoleHierarchy declares the ladder once.

// Sem hierarquia, cada regra lista todos os papéis "acima"
@PreAuthorize("hasAnyRole('USUARIO', 'ANALISTA', 'GERENTE', 'ADMIN')")
public List<Pedido> listar() { ... }

@PreAuthorize("hasAnyRole('GERENTE', 'ADMIN')")
public Pedido aprovar(Long id) { ... }

Configuring the hierarchy

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

  @Bean
  static RoleHierarchy roleHierarchy() {
    return RoleHierarchyImpl.fromHierarchy("""
        ROLE_ADMIN > ROLE_GERENTE
        ROLE_GERENTE > ROLE_ANALISTA
        ROLE_ANALISTA > ROLE_USUARIO
        """);
  }

  // Garante a hierarquia também em @PreAuthorize, @PostAuthorize etc.
  @Bean
  static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
    var handler = new DefaultMethodSecurityExpressionHandler();
    handler.setRoleHierarchy(roleHierarchy);
    return handler;
  }
}

Each line means "the left role includes the right one", transitively. fromHierarchy and the builder below exist since Spring Security 6.3; older versions use setHierarchy(...).

@Bean
static RoleHierarchy roleHierarchy() {
  return RoleHierarchyImpl.withDefaultRolePrefix()
      .role("ADMIN").implies("GERENTE")
      .role("GERENTE").implies("ANALISTA")
      .role("ANALISTA").implies("USUARIO")
      .build();
}

Rules get simple

@PreAuthorize("hasRole('USUARIO')")   // USUARIO, ANALISTA, GERENTE e ADMIN
public List<Pedido> listar() { ... }

@PreAuthorize("hasRole('GERENTE')")   // GERENTE e ADMIN
public Pedido aprovar(Long id) { ... }

It works for permissions too

ROLE_GERENTE > pedidos:aprovar
ROLE_ANALISTA > pedidos:ler

If permissions already come from the database or the IAM, keep the hierarchy between roles only.

Test the ladder

@SpringBootTest
class HierarquiaTest {

  @Autowired PedidoService service;

  @Test
  @WithMockUser(roles = "ADMIN")
  void adminHerdaAprovacaoDoGerente() {
    assertDoesNotThrow(() -> service.aprovar(1L));
  }

  @Test
  @WithMockUser(roles = "ANALISTA")
  void analistaNaoAprova() {
    assertThrows(AccessDeniedException.class, () -> service.aprovar(1L));
  }
}

When not to use it

  • Roles that are areas, not levels (FINANCE and SUPPORT).
  • Separation of duties: inheriting everything can break it.
  • Per-customer rules in SaaS: see multi-tenant RBAC in Spring Boot.

Related articles