concept @prefilter annotation in category spring

appears as: @PreFilter notation, The @PreFilter notation
Spring Security in Action

This is an excerpt from Manning's book Spring Security in Action.

Like in the case of call authorization we discussed in chapter 16, Spring Security also implements filtering by using aspects. Aspects intercept specific method calls and may augment the method call with other instructions. For pre-filtering, an aspect intercepts the methods annotated with the @PreFilter annotation and filters the values in the collection provided as a parameter according to the criteria you define (figure 17.3).

Figure 17.3 With pre-filtering, we decouple the authorization responsibility from the business implementation. The aspect provided by Spring Security only takes care of the authorization rule, and the service method only takes care of the business logic of the use case it implements.

Similar to the @PreAuthorize and @PostAuthorize annotations we discussed in chapter 16, you set the authorization rule as the value of the @PreFilter annotation. In these rules, which you provide as a SpEL expression, you use filterObject to refer to any element inside the collection or array you provide as a parameter to the method.

To see pre-filtering applied, let’s start working on a project. I name this project ssia-ch17-ex1, and you find it in the projects provided with the book. Say you have an application used to buy and sell products. This application’s backend implements an endpoint /sell. The application’s frontend calls this endpoint when a user sells a product. But the logged-in user may only sell the products they own. Let’s implement the very simple scenario of a service method called to sell the products received as a parameter. With this example, you’ll learn how to apply the @PreFilter annotation, as this is the method we’ll use to make sure that the method only receives products owned by the currently logged-in user.

Listing 17.3 Using the @PreFilter annotation in the ProductService class
@Service
public class ProductService {
 
  @PreFilter[CA]    #A
    ("filterObject.owner == authentication.name")
  public List<Product> sellProducts(List<Product> products) {
    // sell products and return the sold products list
    return products;    #B
  }
}