@PostFilter Annotation in Spring Security
@PostFilter removes elements from a collection that a method returns. After the method runs, Spring Security tests every element against a SpEL expression and drops those the current user is not allowed to see, so the caller receives a list that is already trimmed to their permissions.
This tutorial shows how @PostFilter works on lists and maps, using a project task board where confidential tasks are visible only to their assignee and project managers. It also measures the cost that matters most in practice: the method still loads every element, which is why large lists are better filtered in the database query.
1. What Is @PostFilter?
@PostFilter is a method security annotation in org.springframework.security.access.prepost. Once the method returns, the proxy evaluates the expression for each element of the result, available as filterObject, and removes elements for which it is false. For a Map, filterObject is a map entry with key and value.
Supported return types are collections, arrays, maps and open streams; collections and maps must be mutable. It is enabled by @EnableMethodSecurity. The argument-side counterpart is @PreFilter, and the single-object counterpart is @PostAuthorize.
2. Why Use @PostFilter?
- Per-item visibility. One list endpoint can serve users with different rights without separate queries for each role.
- Rules in one place. The visibility rule sits on the service method instead of being repeated in every controller that lists items.
- Safe default. A new caller of the method cannot forget to filter, because the proxy always does it.
3. How @PostFilter Works
Filtering happens in memory, after all data has been loaded. That is fine for short lists. For long or paginated lists it causes two problems: wasted work loading items the user cannot see, and pages that come back with fewer items than requested, because the database filled the page before the filter removed some of them.
4. A Complete Example: A Project Task Board
Public tasks are visible to everyone on the project. Confidential tasks, such as those involving salaries or customers, are visible only to their assignee and to project managers. A second method returns time estimates as a map keyed by task ID. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.
package com.javabytechie.tasks;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.stereotype.Service;
@Service
public class TaskService {
private static final Logger log = LoggerFactory.getLogger(TaskService.class);
public record Task(String id, String title, String assignee, boolean confidential) {}
private final List<Task> board = List.of(
new Task("T-1", "Fix login timeout", "wei", false),
new Task("T-2", "Prepare salary review", "pooja", true),
new Task("T-3", "Upgrade to Java 21", "arjun", false),
new Task("T-4", "Customer escalation: ACME", "wei", true),
new Task("T-5", "Vendor contract renewal", "arjun", true));
@PostFilter("!filterObject.confidential() or filterObject.assignee() == authentication.name or hasRole('PM')")
public List<Task> allTasks() {
log.info("Loaded {} tasks from the store", board.size());
return new ArrayList<>(board); // must be mutable
}
// For maps, filterObject is an entry: use .key and .value
@PostFilter("@taskVisibility.canSee(authentication, filterObject.key)")
public Map<String, Integer> estimatesInHours() {
Map<String, Integer> estimates = new HashMap<>(Map.of("T-1", 3, "T-2", 5, "T-3", 8, "T-4", 2, "T-5", 4));
log.info("Loaded {} estimates from the store", estimates.size());
return estimates;
}
public List<Task> board() {
return board;
}
}
package com.javabytechie.tasks;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
@Component("taskVisibility")
public class TaskVisibility {
private final TaskService tasks;
public TaskVisibility(TaskService tasks) {
this.tasks = tasks;
}
public boolean canSee(Authentication auth, String taskId) {
boolean manager = auth.getAuthorities().stream()
.anyMatch(a -> a.getAuthority().equals("ROLE_PM"));
return tasks.board().stream()
.filter(t -> t.id().equals(taskId))
.anyMatch(t -> !t.confidential() || t.assignee().equals(auth.getName()) || manager);
}
}
package com.javabytechie.tasks;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
private final TaskService tasks;
public TaskController(TaskService tasks) {
this.tasks = tasks;
}
@GetMapping("/api/tasks")
public List<String> tasks() {
return tasks.allTasks().stream().map(t -> t.id() + " " + t.title()).toList();
}
@GetMapping("/api/tasks/estimates")
public Map<String, Integer> estimates() {
return new TreeMap<>(tasks.estimatesInHours()); // sorted for readable output
}
}
package com.javabytechie.tasks;
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.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());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo team only
return new InMemoryUserDetailsManager(
User.withUsername("wei").password(encoder.encode("wei-pass")).roles("DEVELOPER").build(),
User.withUsername("pooja").password(encoder.encode("pooja-pass")).roles("PM").build());
}
}
package com.javabytechie.tasks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TaskBoardApplication {
public static void main(String[] args) {
SpringApplication.run(TaskBoardApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- The list rule keeps a task if it is not confidential, if the caller is its assignee, or if the caller is a project manager.
filterObject.confidential()calls the record accessor of the current task. - A mutable result.
allTasksreturnsnew ArrayList<>(board). Returning the immutableboarddirectly would make filtering fail. - The map rule receives map entries, so it passes
filterObject.key(the task ID) to thetaskVisibilitybean. - Logging in each method shows how many elements were loaded before filtering.
6. Expected Output
$ curl -u wei:wei-pass localhost:8080/api/tasks
HTTP/1.1 200
["T-1 Fix login timeout","T-3 Upgrade to Java 21","T-4 Customer escalation: ACME"]
$ curl -u pooja:pooja-pass localhost:8080/api/tasks
HTTP/1.1 200
["T-1 Fix login timeout","T-2 Prepare salary review","T-3 Upgrade to Java 21","T-4 Customer escalation: ACME","T-5 Vendor contract renewal"]
$ curl -u wei:wei-pass localhost:8080/api/tasks/estimates
HTTP/1.1 200
{"T-1":3,"T-3":8,"T-4":2}
Wei sees the two public tasks and his own confidential one. Pooja, a project manager, sees all five. The estimates map is filtered with the same visibility rules, so Wei gets three entries. The service log tells the other half of the story:
Loaded 5 tasks from the store
Loaded 5 tasks from the store
Loaded 5 estimates from the store
Every request loaded all five items, whatever the caller was allowed to see. With five tasks this costs nothing; with fifty thousand it would load far more data than needed.
7. Filtering in the Query Instead
For large or paginated data, put the visibility rule into the query so the database returns only allowed rows. With Spring Data JPA, the service can pass the current username and role to a repository method:
@Query("""
select t from Task t
where t.confidential = false or t.assignee = :username or :isManager = true
""")
Page<Task> findVisible(@Param("username") String username,
@Param("isManager") boolean isManager,
Pageable pageable);
Pages now contain exactly the requested number of visible rows, and the database can use indexes. Keep @PostFilter for small, bounded collections, or as a second line of defence on top of a filtered query.
8. Common Mistakes and Best Practices
- Immutable results.
List.of(...)andMap.of(...)cannot be filtered; return mutable copies. - Paginated endpoints. Filtering after pagination returns short pages and wrong totals. Filter in the query.
- Large collections. Every element is loaded and every expression is evaluated; measure before using it on big lists.
- Using
@PostAuthorizefor lists. It approves or rejects the whole list. Use@PostFilterto remove individual items. - Map syntax. Use
filterObject.keyandfilterObject.valuefor maps.
9. Summary
@PostFilterremoves elements from a returned collection, array, map or stream after the method runs.filterObjectis the current element; for maps it is an entry withkeyandvalue.- Results must be mutable, and filtering is silent.
- The method always loads every element, so prefer query-level filtering for large or paginated data.
- Use policy beans in the expression to share visibility rules across methods.
10. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between @PostFilter and @PostAuthorize?
@PostAuthorize accepts or rejects the entire return value. @PostFilter keeps the method result but removes the individual elements the user may not see.
Q2. Does @PostFilter work with maps?
Yes. For a Map, filterObject is a map entry, so the expression uses filterObject.key and filterObject.value. The map must be mutable.
Q3. Why should I avoid @PostFilter with pagination?
The database returns a full page first and the filter then removes elements, so pages come back short and totals are wrong. Apply the visibility rule in the query instead.
Q4. Why does @PostFilter throw UnsupportedOperationException?
The method returned an immutable collection such as List.of(...). Return a mutable copy, for example new ArrayList<>(list).
Q5. Does @PostFilter reduce database load?
No. The method loads every element before filtering. To reduce load, filter in the database query and keep @PostFilter for small collections.