MethodSecurityExpressionHandler connects Spring Security’s method-level expression evaluation with custom permission rules. Define it when a PermissionEvaluator must be recognized by method-security expressions. section 11.4
Configure the handler in a method-security configuration class:
- Enable method security with @EnableMethodSecurity. section 11.4
- Create the supplied DefaultMethodSecurityExpressionHandler implementation. section 11.4
- Call setPermissionEvaluator with the custom evaluator, then return the handler bean. section 11.4
Document ownership authorization
A DocumentService method uses @PostAuthorize("hasPermission(returnObject, 'ROLE_admin')"). The configured evaluator grants access to administrators or to the document owner; unauthorized access produces HTTP 403. section 11.4
Listing 11.16 Configuring the PermissionEvaluator in the configuration class
@Configuration
@EnableMethodSecurity
public class ProjectConfig {
private final DocumentsPermissionEvaluator evaluator;
// omitted constructor
@Bean #1
protected MethodSecurityExpressionHandler createExpressionHandler() {
var expressionHandler = #2
new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(
evaluator); #3
return expressionHandler; #4
}
// Omitted definition of the UserDetailsService and PasswordEncoder beans
}
Inspect the complete handler configuration, including DefaultMethodSecurityExpressionHandler construction and PermissionEvaluator registration. section 11.4
