liveBook · Manning

@PostFilter

As explained in Spring Security in Action, Second Edition

@PostFilter is a Spring Security method annotation that filters a method's returned collection or array according to a Spring Expression Language authorization expression.

@PostFilter protects returned data after a method completes. Spring Security allows the method call, then filters its returned collection or array using a SpEL authorization expression. section 12.2

Apply @PostFilter with these constraints:

  • Return a collection or array; other return types are not supported by postfiltering. section 12.2 section 12.4
  • Write the authorization rule as the annotation value, using filterObject for each returned element and authentication for the current security context. section 12.2
  • Prefer database-level filtering for Spring Data repository queries; postfiltering can retrieve every record before filtering and cause memory or performance problems. section 12.3 section 12.4

Filter products by owner

Annotate a service method with @PostFilter("filterObject.owner == authentication.name"). A returned list containing products owned by nikolai and julien is reduced to the current user's products. Calling /find as julien returns chocolate; calling it as nikolai returns beer and candy.

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains aspect-based interception, SpEL variables, supported return types, and repository performance limits.
Examples
Uses owner-filtered products, ProductService, ProductController, authenticated curl requests, and repository query alternatives.
What it assumes
Uses Spring method security, authentication, collections or arrays, and SpEL expressions in its configuration and examples.
What you can do after
Apply it to service methods that return collections or arrays, and recognize when repository queries should filter earlier.
How it connects
Connects @PostFilter with @PreFilter, SpEL, method security, postauthorization, 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.