@PreFilter Annotation in Spring Security
@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
| Attribute or variable | Meaning |
|---|---|
value | The SpEL expression evaluated for each element |
filterObject | The current element inside the expression |
filterTarget | Name of the argument to filter; required when the method has more than one collection argument |
| Supported argument types | Collections, 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;
}
}
package com.javabytechie.photos;
import java.util.Map;
import org.springframework.stereotype.Component;
@Component("photoOwnership")
public class PhotoOwnership {
private final Map<String, String> ownerByPhoto = Map.of(
"P-1", "tanvi", "P-2", "tanvi", "P-9", "kiran");
public boolean owns(String username, String photoId) {
return username.equals(ownerByPhoto.get(photoId));
}
}
package com.javabytechie.photos;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PhotoController {
public record ShareRequest(List<String> photoIds, List<String> friends) {}
private final PhotoService photos;
public PhotoController(PhotoService photos) {
this.photos = photos;
}
@PostMapping("/api/photos/archive")
public Map<String, List<String>> archive(@RequestBody List<String> photoIds) {
return Map.of("archived", photos.archive(new ArrayList<>(photoIds)));
}
@PostMapping("/api/photos/share")
public String share(@RequestBody ShareRequest request) {
return photos.share(new ArrayList<>(request.photoIds()), request.friends());
}
}
package com.javabytechie.photos;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable()); // mobile app client, no browser cookies
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo accounts only
return new InMemoryUserDetailsManager(
User.withUsername("tanvi").password(encoder.encode("tanvi-pass")).roles("USER").build(),
User.withUsername("gopal").password(encoder.encode("gopal-pass")).roles("USER", "MODERATOR").build());
}
}
package com.javabytechie.photos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PhotoApplication {
public static void main(String[] args) {
SpringApplication.run(PhotoApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- 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. - Mutable input. The controller passes
new ArrayList<>(...), because filtering removes elements in place and an immutable list would throw an exception. filterTarget = "photoIds"is required inshare, 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.- The method body trusts its input completely, because only allowed elements reach it.
6. Expected Output
$ 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
| Advantages | Limitations |
|---|---|
| Safe bulk operations without manual loops | Silent: the caller gets no error for removed items |
| Method body works only with allowed data | One expression evaluation (and maybe a lookup) per element |
| Reuses policy beans for ownership rules | Requires mutable collections and modifies the caller's collection |
| Works on collections, arrays, maps and streams | Needs filterTarget when several collections are passed |
9. Common Mistakes and Best Practices
- Immutable collections.
List.of(...)cannot be filtered; pass anArrayListor 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
@PreAuthorizeand 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
@PreAuthorizefor the operation itself, for examplehasRole('USER'), and use the filter only for the items.
10. Summary
@PreFilterevaluates an expression for each element of a collection argument and removes failing elements.- Inside the expression,
filterObjectis the current element. - Use
filterTargetto 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
@PreAuthorizewhen the whole request should be accepted or rejected.
11. References
Frequently Asked Questions (FAQ)
Q1. What does @PreFilter do in Spring Security?
It filters a collection argument before the method runs, removing every element for which the SpEL expression is false. The method receives only the remaining elements.
Q2. What is filterObject?
filterObject is the SpEL variable holding the current element while @PreFilter or @PostFilter evaluates its expression for each element.
Q3. When do I need filterTarget?
When the method has more than one collection (or array, map or stream) argument. filterTarget names the argument that should be filtered.
Q4. Does @PreFilter return 403 when elements are removed?
No. Removed elements disappear silently and the method runs with the rest, even if nothing is left. Use @PreAuthorize if you want the request to fail instead.
Q5. Why does @PreFilter throw UnsupportedOperationException?
The collection passed to the method is immutable, for example created by List.of(...). Pass a mutable copy such as new ArrayList<>(list).