00:00

@PreFilter Annotation in Spring Security

Last updated:

@PreFilter removes elements from a collection argument before the method sees it. Each element is tested against a SpEL expression, and elements for which the expression is false are taken out of the collection. The method then runs with only the elements the caller is allowed to touch.

It is designed for bulk operations, such as "archive these 20 photos", where some IDs in the request may belong to someone else. This tutorial explains how filterObject and filterTarget work, shows the behaviour that surprises people (filtered elements are dropped silently, without an error), and covers when a filter is the wrong tool.

1. What Is @PreFilter?

@PreFilter is a method security annotation in org.springframework.security.access.prepost. Before the method runs, the proxy iterates over the chosen argument and evaluates the expression once per element, with the element available as filterObject. Elements that fail are removed from the collection in place.

It is enabled together with the other pre/post annotations by @EnableMethodSecurity. The output counterpart is @PostFilter, which filters a returned collection.

2. Why Use @PreFilter?

  • Bulk requests mix allowed and forbidden items. Rejecting the whole request is unfriendly; trusting it is unsafe. Filtering keeps only the items the user owns.
  • Business code stays clean. The service method can assume every element is allowed and does not need its own ownership loop.
  • Consistent rules. The expression can call the same policy bean used elsewhere, so ownership is defined once.

Because filtering is silent, it is not the right tool when the caller must be told that part of the request was refused; see the pitfalls below.

3. How @PreFilter Works

@PreFilter removing elements before the method runsThe caller passes P-1, P-2 and P-9. The expression is evaluated for each element; P-9 belongs to another user and is removed. The method receives only P-1 and P-2. Argument [P-1, P-2, P-9] P-1: owned by tanvi kept P-2: owned by tanvi kept P-9: owned by kiran removed archive(...) receives [P-1, P-2]
Figure 1: each element is tested; failing elements are removed before the method body runs.
Attribute or variableMeaning
valueThe SpEL expression evaluated for each element
filterObjectThe current element inside the expression
filterTargetName of the argument to filter; required when the method has more than one collection argument
Supported argument typesCollections, arrays, maps and streams; collections and maps must be mutable

Since filtering changes the argument in place, the caller's collection is modified too. Pass a copy if the caller still needs the original.

4. A Complete Example: Bulk Archiving in a Photo App

Users of a photo-sharing app select several photos and archive them in one request. Moderators may archive any photo. A second operation shares photos with friends and has two list arguments. The API is called by the mobile app with HTTP Basic and no cookies, so CSRF protection is disabled. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.

package com.javabytechie.photos;

import java.util.List;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Service;

@Service
public class PhotoService {

    // Owners archive their own photos; moderators may archive any
    @PreFilter("hasRole('MODERATOR') or @photoOwnership.owns(authentication.name, filterObject)")
    public List<String> archive(List<String> photoIds) {
        return List.copyOf(photoIds);       // only allowed IDs arrive here
    }

    // Two collections: filterTarget says which one to filter
    @PreFilter(value = "@photoOwnership.owns(authentication.name, filterObject)", filterTarget = "photoIds")
    public String share(List<String> photoIds, List<String> friends) {
        return "Shared " + photoIds + " with " + friends;
    }
}

5. Step-by-Step Code Explanation

  1. The archive filter keeps an element if the caller is a moderator or owns the photo. @photoOwnership.owns(authentication.name, filterObject) calls the policy bean once per element.
  2. Mutable input. The controller passes new ArrayList<>(...), because filtering removes elements in place and an immutable list would throw an exception.
  3. filterTarget = "photoIds" is required in share, which has two list arguments. Without it, Spring Security cannot know which one to filter and fails at call time. The friends list is left untouched.
  4. The method body trusts its input completely, because only allowed elements reach it.

6. Expected Output

Terminal
$ curl -u tanvi:tanvi-pass -X POST localhost:8080/api/photos/archive -H 'Content-Type: application/json' -d '["P-1","P-2","P-9"]'
HTTP/1.1 200
{"archived":["P-1","P-2"]}

$ curl -u tanvi:tanvi-pass -X POST localhost:8080/api/photos/archive -H 'Content-Type: application/json' -d '["P-9"]'
HTTP/1.1 200
{"archived":[]}

$ curl -u gopal:gopal-pass -X POST localhost:8080/api/photos/archive -H 'Content-Type: application/json' -d '["P-9"]'
HTTP/1.1 200
{"archived":["P-9"]}

$ curl -u tanvi:tanvi-pass -X POST localhost:8080/api/photos/share -H 'Content-Type: application/json' -d '{"photoIds":["P-1","P-9"],"friends":["kiran","neel"]}'
HTTP/1.1 200
Shared [P-1] with [kiran, neel]

Tanvi's request for three photos archives only her two; P-9 belongs to Kiran and was removed. Her request for P-9 alone succeeds with status 200 and an empty list: nothing was archived, and nothing told her why. Gopal, a moderator, can archive P-9. In the share request, only the photo list was filtered; both friends remain.

7. When to Use @PreFilter

Use @PreFilter when ignoring forbidden items is an acceptable answer: selecting many photos and archiving the ones you own, or marking a set of notifications as read. The user experience is forgiving and the data stays safe.

Prefer an explicit @PreAuthorize check that rejects the whole request when a forbidden item points to a mistake or an attack, for example a payment batch that includes another customer's invoice. In that situation, a silent partial success would hide a problem that someone needs to investigate.

8. Advantages and Limitations

AdvantagesLimitations
Safe bulk operations without manual loopsSilent: the caller gets no error for removed items
Method body works only with allowed dataOne expression evaluation (and maybe a lookup) per element
Reuses policy beans for ownership rulesRequires mutable collections and modifies the caller's collection
Works on collections, arrays, maps and streamsNeeds filterTarget when several collections are passed

9. Common Mistakes and Best Practices

  • Immutable collections. List.of(...) cannot be filtered; pass an ArrayList or copy first.
  • Silent partial success. If the client must know which items were refused, compare the input and output in the controller and return both, or check with @PreAuthorize and reject the whole request.
  • N lookups for N elements. For large batches, load ownership for all IDs in one query inside the policy bean instead of one query per element.
  • Missing filterTarget. Add it whenever the method has more than one collection argument.
  • Filtering instead of authorising the operation. Combine with @PreAuthorize for the operation itself, for example hasRole('USER'), and use the filter only for the items.

10. Summary

  • @PreFilter evaluates an expression for each element of a collection argument and removes failing elements.
  • Inside the expression, filterObject is the current element.
  • Use filterTarget to choose the argument when the method has several collections.
  • Filtering is silent and in place, so pass mutable copies and inform clients when needed.
  • It is meant for bulk operations; use @PreAuthorize when the whole request should be accepted or rejected.

11. References