@PostAuthorize Annotation in Spring Security
@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 runs | Before the method | After the method returns |
| Can use | Arguments, user, beans | Arguments, user, beans and returnObject |
| Method body runs when denied? | No | Yes |
| Suitable for writes | Yes | No: changes happen before the check |
| Typical use | Role checks, argument ownership | Ownership of a loaded object |
4. How @PostAuthorize Works
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;
}
}
package com.javabytechie.telehealth;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LabReportController {
private final LabReportService reports;
public LabReportController(LabReportService reports) {
this.reports = reports;
}
@GetMapping("/api/lab-reports/{id}")
public LabReportService.LabReport report(@PathVariable String id) {
return reports.reportFor(id);
}
}
package com.javabytechie.telehealth;
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 accounts only
return new InMemoryUserDetailsManager(
User.withUsername("asha").password(encoder.encode("asha-pass")).roles("PATIENT").build(),
User.withUsername("dr-iyer").password(encoder.encode("iyer-pass")).roles("DOCTOR").build());
}
}
package com.javabytechie.telehealth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TelehealthApplication {
public static void main(String[] args) {
SpringApplication.run(TelehealthApplication.class, args);
}
}
6. Step-by-Step Code Explanation
- 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. returnObjectis theLabReportrecord, soreturnObject.patient()calls its accessor.- Missing reports throw a 404 before the post check, so
returnObjectis nevernull. 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. - The log line records every time the method body runs, which makes the "after" nature of the check visible.
7. Expected Output
$ 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:
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
| Advantages | Limitations |
|---|---|
| Rules can use fields of the loaded object | The method always runs, including its side effects |
| Avoids loading the same record twice for a check | Work is wasted for denied callers |
Same SpEL features as @PreAuthorize | Not suitable for collections; use @PostFilter for those |
| Keeps ownership rules close to the data access | A 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
@PostAuthorizechanges data before deciding the caller was not allowed to. Load and check first, then write, or use@PreAuthorizewith a policy bean. nullresults. An expression likereturnObject.patient()fails onnull. Throw for missing records or guard withreturnObject != null and ....- Returning collections.
returnObjectwould 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,
@PreAuthorizeavoids the wasted work.
10. Summary
@PostAuthorizeevaluates its expression after the method returns, with the result asreturnObject.- If the expression is false, the result is discarded and the caller receives 403.
- The method body always runs, so use
@PostAuthorizeonly for side-effect-free reads. - Handle
nulland missing records before the expression runs. - For collections use
@PostFilter; for checks on arguments use@PreAuthorize.
11. References
Frequently Asked Questions (FAQ)
Q1. What is returnObject in @PostAuthorize?
returnObject is a SpEL variable that holds the value returned by the method. The expression can read its fields or call its methods, for example returnObject.owner() == authentication.name.
Q2. Does the method run if @PostAuthorize denies access?
Yes. The method runs completely; only its return value is withheld and an AuthorizationDeniedException is thrown. Any side effects have already happened.
Q3. When should I use @PostAuthorize instead of @PreAuthorize?
When the decision depends on data in the returned object and the method has no side effects, such as loading a single record by ID. Use @PreAuthorize for writes and for checks that only need the arguments.
Q4. Can @PostAuthorize filter a list?
No. It approves or rejects the whole return value. Use @PostFilter to remove individual elements from a returned collection.
Q5. What HTTP status does a failed @PostAuthorize produce?
In a web request, the AuthorizationDeniedException is handled by Spring Security and results in 403 Forbidden.