java / intermediate
Snippet
Evaluating Domain-Level Access with Custom Spring Security PermissionEvaluators
Custom PermissionEvaluator implementations enable fine-grained access control within SpEL security expressions such as @PreAuthorize("hasPermission(#document, 'WRITE')"), decoupling domain logic checks from controller code.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Componentpublic class DocumentPermissionEvaluator implements PermissionEvaluator {@Overridepublic boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {if (targetDomainObject instanceof Document doc && permission instanceof String perm) {return doc.getOwnerId().equals(auth.getName()) || "READ".equalsIgnoreCase(perm);}return false;}@Overridepublic boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {return false;}}
spring
Breakdown
1
public class DocumentPermissionEvaluator implements PermissionEvaluator
Implements Spring Security's interface for evaluating permissions against specific domain objects.
2
if (targetDomainObject instanceof Document doc && permission instanceof String perm)
Uses Java pattern matching for instanceof to safely type-check and cast the target object and permission.
3
return doc.getOwnerId().equals(auth.getName()) || "READ".equalsIgnoreCase(perm);
Applies business authorization rules comparing the authenticated principal with the document owner.