Preauthorization checks authorization rules before a protected method executes. Spring Security intercepts the call through an aspect, delegates only when the rules pass, and otherwise raises AccessDeniedException. section 11.1.1
Apply preauthorization when a method should not run unless its caller satisfies a condition:
- Enable method security with @EnableMethodSecurity; method security is disabled by default. section 11.1.2
- Annotate the protected method with @PreAuthorize and provide a Spring Expression Language (SpEL) rule. section 11.2
- Use authorities such as hasAuthority('write') or compare method parameters with authentication.principal.username. section 11.2
- Separate complex authorization logic into another class, commonly through a PermissionEvaluator. section 11.5
Protecting a service method
A service can require write authority before returning a value: @PreAuthorize("hasAuthority('write')") on getName() allows Emma, who has write authority, to receive "Hello, Fantastico" through /hello, while Natalie receives a 403 response. Parameter-based rules can instead enforce ownership: @PreAuthorize("#name == authentication.principal.username") allows a user to retrieve only that user's secret names. section 11.2
