0 day streak
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
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 resource
return true;
}
@Override
public void setFilterObject(Object filterObject) {}
@Override
public Object getFilterObject() { return null; }
@Override
public void setReturnObject(Object returnObject) {}
@Override
public Object getReturnObject() { return null; }
@Override
public 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)").