hasPermission() delegates a method-level authorization decision to a PermissionEvaluator. It supports rules such as allowing administrators or document owners to access a returned document. section 11.4
Use one of two evaluator contracts:
- Pass the subject object and a permission value, as with hasPermission(returnObject, 'ROLE_admin'). section 11.4
- Pass an identifier, object type, and permission value, as with hasPermission(#code, 'document', 'ROLE_admin'). section 11.4
- Register the custom PermissionEvaluator through a MethodSecurityExpressionHandler before using the expression. section 11.4
Owner-or-admin document access
A DocumentService method uses @PostAuthorize("hasPermission(returnObject, 'ROLE_admin')"). The evaluator grants access when the authenticated user has the supplied authority or owns the returned document. The identifier form instead evaluates before invocation and retrieves the document by code. Requests by the owner succeed; requests by another non-admin user receive HTTP 403. section 11.4
Listing 11.15 Implementing the authorization rule
@Component
public class DocumentsPermissionEvaluator
implements PermissionEvaluator { #1
@Override
public boolean hasPermission(
Authentication authentication,
Object target,
Object permission) {
Document document = (Document) target; #2
String p = (String) permission; #3
boolean admin = #4
authentication.getAuthorities()
.stream()
.anyMatch(a -> a.getAuthority().equals(p));
return admin || #5
document.getOwner()
.equals(authentication.getName());
}
@Override
public boolean hasPermission(Authentication authentication,
Serializable targetId,
String targetType,
Object permission) {
return false; #6
}
}
Inspect the evaluator implementation that checks authorities and document ownership. section 11.4
