liveBook · Manning

@PostAuthorize

As explained in Spring Security in Action, Second Edition

PostAuthorize is a Spring Security annotation that authorizes access to a method's result by evaluating an expression after the method executes.

@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

How Spring Security in Action, Second Edition covers it

How deep it goes
Defines annotation use, SpEL returnObject access, PermissionEvaluator delegation, and HTTP outcomes, but not framework internals.
Examples
Uses employee roles, document ownership, administrator permissions, REST endpoints, curl requests, and HTTP 403 responses.
What it assumes
Assumes basic Spring and Java, while demonstrating method-security enablement, SpEL expressions, and permission-evaluator configuration.
What you can do after
Apply returned-value authorization with @PostAuthorize and delegate complex checks through a configured PermissionEvaluator.
How it connects
Links method security with SpEL, @PreAuthorize, PermissionEvaluator, @RolesAllowed, and @Secured.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.