java / expert
Snippet
Extending Method Security with Custom SpEL Expressions
By extending SecurityExpressionRoot, you can define custom domain-specific SpEL functions (like isResourceOwner) that can be used directly in @PreAuthorize annotations, centralizing complex authorization logic.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class CustomSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {public CustomSecurityExpressionRoot(Authentication authentication) {super(authentication);}public boolean isResourceOwner(Long resourceId) {// Logic to check if the current user owns the specific resourcereturn true;}@Overridepublic void setFilterObject(Object filterObject) {}@Overridepublic Object getFilterObject() { return null; }@Overridepublic void setReturnObject(Object returnObject) {}@Overridepublic Object getReturnObject() { return null; }@Overridepublic Object getThis() { return this; }}
spring
Breakdown
1
extends SecurityExpressionRoot
Inherits base security evaluation logic like hasRole() and isAuthenticated().
2
implements MethodSecurityExpressionOperations
Required interface for evaluating expressions on methods.
3
public boolean isResourceOwner(Long resourceId)
Custom SpEL function accessible via @PreAuthorize("isResourceOwner(#id)").