@PreFilter protects a method from processing unauthorized elements by filtering a collection or array before invocation. Its SpEL rule separates authorization from business logic, so the method receives only values that satisfy the rule. section 12.1 section 12.4
Apply @PreFilter with these practical constraints:
- Enable method security and place the annotation on the protected method. section 12.1
- Write the authorization condition as SpEL; use filterObject for each collection or array element and authentication for the current user. section 12.1
- Provide a mutable collection because the intercepting aspect changes the supplied parameter; immutable collections can cause UnsupportedOperationException. section 12.1
- Use query-level filtering for repository data when possible instead of retrieving broad results and filtering them afterward. section 12.3
Selling only owned products
A service can accept a product list while allowing only products owned by the authenticated user: @PreFilter("filterObject.owner == authentication.name") on sellProducts(List<Product> products). A request authenticated as nikolai receives only the beer and candy entries; julien receives only chocolate. section 12.1
Figure 12.3 With prefiltering, we decouple the authorization responsibility from the business implementation. The aspect provided by Spring Security only takes care of the authorization rules, and the service method only takes care of the business logic of the use case it implements.
Shows how an aspect intercepts the method call and keeps authorization filtering separate from business logic. section 12.1
