liveBook · Manning

@PreFilter

As explained in Spring Security in Action, Second Edition

@PreFilter is a Spring Security annotation that filters elements of a method input collection or array by evaluating an authorization expression before method invocation.

@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

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains aspect interception, SpEL variables, configuration, examples, and mutable-collection behavior, while deferring broader filtering internals.
Examples
Uses product ownership, /sell requests, authenticated users, mutable lists, and repository queries as concrete demonstrations.
What you can do after
Apply it via Spring Security annotations to restrict collection or array inputs before method execution.
How it connects
Connects method security, SpEL, authentication, @PreAuthorize, @PostAuthorize, @PostFilter, and Spring Data repositories.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.