00:00

@PostFilter Annotation in Spring Security

Last updated:

@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

@PostFilter removing elements after the method returnsThe method loads five tasks. The proxy evaluates the expression for each; for developer wei, two confidential tasks assigned to others are removed, and three tasks are returned. allTasks() loads 5 tasks T-1 public: kept T-2 confidential, pooja's: removed T-3 public: kept T-4 confidential, wei's own: kept wei receives T-1, T-3, T-4 (T-5 also removed)
Figure 1: the method loads everything; the proxy removes what the user may not see.

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;
    }
}

5. Step-by-Step Code Explanation

  1. 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.
  2. A mutable result. allTasks returns new ArrayList<>(board). Returning the immutable board directly would make filtering fail.
  3. The map rule receives map entries, so it passes filterObject.key (the task ID) to the taskVisibility bean.
  4. Logging in each method shows how many elements were loaded before filtering.

6. Expected Output

Terminal
$ 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:

Terminal
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:

TaskRepository.java (sketch)
@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(...) and Map.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 @PostAuthorize for lists. It approves or rejects the whole list. Use @PostFilter to remove individual items.
  • Map syntax. Use filterObject.key and filterObject.value for maps.

9. Summary

  • @PostFilter removes elements from a returned collection, array, map or stream after the method runs.
  • filterObject is the current element; for maps it is an entry with key and value.
  • 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