0 day streak
java / intermediate
Snippet

Evaluating Hierarchical Role Permissions with Method Security Expressions

Spring Security's method security expressions allow fine-grained access control using Spring Expression Language (SpEL). By registering a custom RoleHierarchy bean with DefaultMethodSecurityExpressionHandler, higher-level roles implicitly inherit permissions granted to lower-level roles. This prevents redundant authorization declarations across business services and enforces authorization logic directly at the method invocation boundary.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public RoleHierarchy roleHierarchy() {
return RoleHierarchyImpl.withDefaultRolePrefix()
.role("ADMIN").implies("MANAGER")
.role("MANAGER").implies("USER")
.build();
}
@Bean
public MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setRoleHierarchy(roleHierarchy);
return expressionHandler;
}
}
@Service
public class ReportService {
@PreAuthorize("hasRole('USER') and #reportType != 'FINANCIAL'")
public Report generateReport(String reportType) {
return new Report(reportType, "Generated data");
}
}
spring
Breakdown
1
return RoleHierarchyImpl.withDefaultRolePrefix().role("ADMIN").implies("MANAGER").role("MANAGER").implies("USER").build();
Defines an explicit role hierarchy where ADMIN automatically includes MANAGER privileges, which in turn include USER privileges.
2
expressionHandler.setRoleHierarchy(roleHierarchy);
Injects the role hierarchy configuration into the method security expression evaluation pipeline.
3
@PreAuthorize("hasRole('USER') and #reportType != 'FINANCIAL'")
Evaluates a SpEL expression before execution, verifying role eligibility via hierarchy and checking runtime method parameters.