00:00

@PostAuthorize Annotation in Spring Security

Last updated:

@PostAuthorize checks a rule after a method has run, using the value the method returned. It answers questions that cannot be asked in advance, such as "does this lab report belong to the patient who asked for it?", when the owner is only known once the report has been loaded.

This tutorial explains how returnObject works, when @PostAuthorize is the right choice and when it is not, and demonstrates its most important property on a telehealth service: the method body always runs, even when the caller is denied the result.

1. What Is @PostAuthorize?

@PostAuthorize is a method security annotation that holds a SpEL expression. Spring Security's AuthorizationManagerAfterMethodInterceptor calls the real method, then evaluates the expression with the result available as returnObject. If the expression is false, the result is discarded and AuthorizationDeniedException is thrown, which a web request turns into 403.

Everything available in @PreAuthorize is available here too: roles, authentication, method arguments and bean references. Method security must be enabled with @EnableMethodSecurity.

2. Why Is @PostAuthorize Needed?

Many access rules depend on data inside the record: the patient on a report, the owner of a document, the tenant of an invoice. With only an ID as input, a "pre" check cannot know the answer without loading the record itself. @PostAuthorize lets the method load it normally and applies the rule to what came back.

It is most useful for read operations that return a single object, where loading twice (once to check, once to return) would be wasteful and where running the method has no side effects.

3. @PreAuthorize vs @PostAuthorize

@PreAuthorize@PostAuthorize
When the check runsBefore the methodAfter the method returns
Can useArguments, user, beansArguments, user, beans and returnObject
Method body runs when denied?NoYes
Suitable for writesYesNo: changes happen before the check
Typical useRole checks, argument ownershipOwnership of a loaded object

4. How @PostAuthorize Works

@PostAuthorize sequenceThe proxy calls the real method first. The method loads the report. The proxy then evaluates the expression with returnObject; if true the report is returned, if false an AuthorizationDeniedException produces 403. Caller reportFor("LR-2") Proxy call method first Real method loads the report side effects happen here Expression true return the report Expression false 403, result dropped
Figure 1: the method always runs; the expression decides whether its result is returned.

Inside the expression, returnObject is the method's return value. If the method returns Optional, returnObject is the Optional itself, so write returnObject.get().patient() or, better, return the object directly and let the caller handle a missing record.

5. A Complete Example: Lab Reports in a Telehealth App

Patients may read their own lab reports, and doctors may read reports of patients assigned to them. The service loads a report by ID and logs each load, so we can see when the method body runs. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.

package com.javabytechie.telehealth;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

@Service
public class LabReportService {

    private static final Logger log = LoggerFactory.getLogger(LabReportService.class);

    public record LabReport(String id, String patient, String doctor, String test, String result) {}

    private final Map<String, LabReport> reports = Map.of(
        "LR-1", new LabReport("LR-1", "asha", "dr-mehta", "HbA1c", "5.4 %"),
        "LR-2", new LabReport("LR-2", "rohit", "dr-iyer", "Vitamin D", "31 ng/mL"));

    @PostAuthorize("returnObject.patient() == authentication.name"
        + " or (hasRole('DOCTOR') and returnObject.doctor() == authentication.name)")
    public LabReport reportFor(String id) {
        LabReport report = reports.get(id);
        if (report == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        log.info("Loaded lab report {} for patient {}", id, report.patient());
        return report;
    }
}

6. Step-by-Step Code Explanation

  1. The expression allows the result if the report's patient is the caller, or if the caller is a doctor and the report's doctor is the caller. The two string parts are joined with + only to keep lines short.
  2. returnObject is the LabReport record, so returnObject.patient() calls its accessor.
  3. Missing reports throw a 404 before the post check, so returnObject is never null. Be aware that this tells any logged-in user which IDs exist; if that matters, return 403 or 404 consistently for both missing and forbidden records.
  4. The log line records every time the method body runs, which makes the "after" nature of the check visible.

7. Expected Output

Terminal
$ curl -u asha:asha-pass localhost:8080/api/lab-reports/LR-1
HTTP/1.1 200
{"id":"LR-1","patient":"asha","doctor":"dr-mehta","test":"HbA1c","result":"5.4 %"}

$ curl -u asha:asha-pass localhost:8080/api/lab-reports/LR-2
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:40.160Z","status":403,"error":"Forbidden","path":"/api/lab-reports/LR-2"}

$ curl -u dr-iyer:iyer-pass localhost:8080/api/lab-reports/LR-2
HTTP/1.1 200
{"id":"LR-2","patient":"rohit","doctor":"dr-iyer","test":"Vitamin D","result":"31 ng/mL"}

$ curl -u dr-iyer:iyer-pass localhost:8080/api/lab-reports/LR-1
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:40.295Z","status":403,"error":"Forbidden","path":"/api/lab-reports/LR-1"}

Asha may read her own report and is refused Rohit's. Dr. Iyer may read Rohit's report, which is assigned to him, but not Asha's. Now look at the service log:

Terminal
Loaded lab report LR-1 for patient asha
Loaded lab report LR-2 for patient rohit
Loaded lab report LR-2 for patient rohit
Loaded lab report LR-1 for patient asha

There are four log lines for four requests, including the two that ended in 403. The method body ran every time; only the result was withheld. For a read, that is acceptable. For a method that sends an email, updates a counter or writes to the database, the side effect would already have happened when access is denied.

8. Advantages and Limitations

AdvantagesLimitations
Rules can use fields of the loaded objectThe method always runs, including its side effects
Avoids loading the same record twice for a checkWork is wasted for denied callers
Same SpEL features as @PreAuthorizeNot suitable for collections; use @PostFilter for those
Keeps ownership rules close to the data accessA different error for "missing" and "forbidden" can reveal which IDs exist

9. Common Mistakes and Best Practices

  • Using it on writes. An update annotated with @PostAuthorize changes data before deciding the caller was not allowed to. Load and check first, then write, or use @PreAuthorize with a policy bean.
  • null results. An expression like returnObject.patient() fails on null. Throw for missing records or guard with returnObject != null and ....
  • Returning collections. returnObject would be the whole list. Use @PostFilter to remove individual elements.
  • Masking instead of refusing. To return a partly hidden object rather than 403, combine method security with @HandleAuthorizationDenied, shown in method-level security.
  • Prefer a pre-check when it is cheap. If the ownership can be checked from arguments or a light query, @PreAuthorize avoids the wasted work.

10. Summary

  • @PostAuthorize evaluates its expression after the method returns, with the result as returnObject.
  • If the expression is false, the result is discarded and the caller receives 403.
  • The method body always runs, so use @PostAuthorize only for side-effect-free reads.
  • Handle null and missing records before the expression runs.
  • For collections use @PostFilter; for checks on arguments use @PreAuthorize.

11. References