@PostAuthorize protects a method’s returned value by evaluating a SpEL authorization rule after the method executes. This suits data-dependent decisions: the application must retrieve the result before it knows whether the caller may receive it. section 11.3
Apply postauthorization in a small Spring Security application as follows:
- Enable method security with @EnableMethodSecurity. section 11.3 section 11.5
- Annotate the service method with @PostAuthorize and provide a SpEL expression. section 11.3
- Reference the returned value through returnObject; reject access when the expression evaluates to false. section 11.3
- Prefer @PreAuthorize when authorization can be decided from the caller and method arguments before execution. section 11.5
Authorize employee details by returned roles
A BookService method can use @PostAuthorize("returnObject.roles.contains('reader')") after retrieving an Employee. Emma’s record includes the reader role and is returned; Natalie’s record does not, so the request receives HTTP 403. The method is still called before the result is rejected. section 11.3
Delegate complex checks to PermissionEvaluator
A DocumentService method can use @PostAuthorize("hasPermission(returnObject, 'ROLE_admin')"). A PermissionEvaluator then permits an administrator or the document owner, keeping complex authorization logic outside the service method. section 11.4
Figure 11.7 With postauthorization, we don’t protect the method from being called, but we protect the returned value from being exposed if the defined authorization rules aren’t respected.
Visualizes the boundary protected by postauthorization: method execution proceeds, but the returned value is exposed only when the rule succeeds. section 11.3
