How @PostFilter and @PreFilter work

Being newer to spring annotations, I need clarification for the code below.

@PostFilter("hasPermission(filterObject, 'READ') or hasRole('ROLE_ADMIN')") public List<User> getUsers(String orderByInsertionDate, Integer numberDaysToLookBack) throws AppException 

;

Thus, this means that the list of users returned by getUsers will contain only those elements that have full "READ" access to the caller, or the caller has the role "ROLE_ADMIN" . Thanks.

+5
source share
1 answer

@PreFilter and @PostFilter are designed to be used with Spring protection to be able to filter collections or arrays based on authorization.

For this to work, you need to use expression-based access control in Spring Security (as in your example)

@PreFilter - Filters a collection or arrays before executing a method.

@PostFilter - Filters the returned collection or arrays after the method is executed.

So let's say your getUser() returns a list of users. Spring Security will iterate over the list and remove any elements for which the application expression is false (for example, it is not an administrator and does not have read permission)

filterObject is an inline object in which the filter operation is performed, and you can apply various conditions to this object (basically all inline expressions are available here, for example, principal , authentication ), for example, you can do

 @PostFilter ("filterObject.owner == authentication.name") 

Although these filters are useful, they are really inefficient for large datasets, and basically you lose control over your result; instead, Spring controls the result.

+10
source

Source: https://habr.com/ru/post/1213866/


All Articles