liveBook · Manning

Postfiltering

As explained in Spring Security in Action, Second Edition

Postfiltering is filtering applied to a method's returned data before the caller receives it.

Postfiltering applies authorization after a method executes. The method call succeeds, but the framework removes unauthorized elements from its returned collection or array before the caller receives the result. Unlike postauthorization, it does not reject the entire call when some returned values violate the rule. section 12.0 section 12.2

Implement postfiltering by following these constraints:

  • Enable method security, then annotate a method with @PostFilter. section 12.2
  • Return a collection or array; postfiltering does not apply to a single returned object. section 12.0 section 12.4
  • Write the authorization condition as a SpEL expression, using filterObject for each returned element and authentication for the security context. section 12.2
  • Prefer database-level conditions for repository queries instead of loading a large result set and filtering it in application memory. section 12.3

Returning only the caller's products

A service can expose @PostFilter("filterObject.owner == authentication.name") on findProducts(), which returns products owned by different users. A request authenticated as julien receives only chocolate; a request authenticated as nikolai receives beer and candy. For a Spring Data repository, move the ownership condition into the query with authentication.name so the data source returns only authorized records. section 12.2 section 12.3

Figure 12.7 Postfiltering. An aspect intercepts the collection returned by the protected method and filters the values that don’t follow the rules you provide. Unlike postauthorization, postfiltering doesn’t throw an exception to the caller when the returned value doesn’t follow the authorization rules.

Shows the aspect intercepting a returned collection, removing values that fail the rule, and avoiding the exception produced by postauthorization. section 12.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains annotation-based filtering, SpEL variables, return-type limits, and database-level alternatives for repositories.
Examples
Uses owner-filtered products, authenticated users, @PostFilter expressions, curl requests, and repository queries.
What it assumes
Assumes basic method security and authorization concepts while teaching collection filtering and its SpEL references.
What you can do after
Apply it via @PostFilter to restrict returned collections, or diagnose repository performance by moving conditions into queries.
How it connects
Connects method security, postauthorization, prefiltering, SpEL, Spring Data repositories, and database queries.

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.