@PreFilter & @PostFilter

@PreFilter & @PostFilter are Spring Security annotations used to filter collections or arrays before or after a method executes — based on security expressions.


🧩 @PreFilter

Filters input collection before the method runs.

Example:

@PreFilter("filterObject.owner == authentication.name")
public void deleteFiles(List<File> files) {
    // only files owned by current user remain in 'files'
    files.forEach(fileRepo::delete);
}

Here, only files where file.owner equals the logged-in username are passed to the method.


🧩 @PostFilter

Filters output collection after the method returns.

Example:

@PostFilter("filterObject.owner == authentication.name")
public List<File> getAllFiles() {
    return fileRepo.findAll();
}

Only files owned by the authenticated user will be included in the response.


Key Points:

  • Both use Spring Expression Language (SpEL).
  • filterObject represents each item in the collection.
  • Often used in service layer methods with @EnableGlobalMethodSecurity(prePostEnabled = true).

Leave a Reply