liveBook · Manning

Query filtering

As explained in Spring Security in Action, Second Edition

Database-level filtering is the application of selection criteria within a database query so that only permitted records are returned.

Query filtering applies authorization criteria inside a database query so the data source returns only permitted records. In Spring Data repositories, this avoids loading unauthorized rows and filtering them afterward in application memory. section 12.3 section 12.4

Choose query filtering instead of repository-level postfiltering when:

  • A repository method could retrieve many records, because postfiltering may create heavy memory and performance costs. section 12.3
  • The permitted records can be expressed as a repository query condition, such as matching the current authentication name to an owner field. section 12.3
  • Application-level filtering is unavoidable at the service layer, but repository filtering can retrieve only the required records at the source. section 12.3

Restrict products by authenticated owner

A ProductRepository query combines a name condition with `p.owner=?#{authentication.name}`. Searching for `c` returns candy to nikolai and chocolate to julien, without retrieving the other user's product for later filtering. section 12.3

Figure 12.10 In our scenario, we start by implementing the application using @PostFilter to filter products based on their owner. Then we change the implementation to add the condition directly on the query. This way, we make sure the application only gets from the source the needed records.

Compare repository postfiltering with adding the ownership condition directly to the query. section 12.3

How Spring Security in Action, Second Edition covers it

How deep it goes
Shows the performance problem, compares postfiltering, and implements an authenticated-owner condition with Spring Data query SpEL.
Examples
Uses a Product entity, owner-filtered product searches, MySQL records, and authenticated curl requests.
What it assumes
Assumes basic Spring Data repositories and authentication, while demonstrating the required security evaluation context configuration.
What you can do after
Operate/configure Spring Data repositories to return only records owned by the authenticated user.
How it connects
Connects Spring Data repositories with Spring Security, @PostFilter, method security, and SpEL.

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.