@PreAuthorize protects a method by evaluating a Spring Expression Language (SpEL) authorization rule before the method executes. Enable method security with @EnableMethodSecurity; otherwise, method-level authorization is disabled. section 11.2 section 11.5
Apply it to method-level authorization by:
- Checking authorities with expressions such as hasAuthority(), hasAnyAuthority(), hasRole(), or hasAnyRole(). section 11.2
- Referencing method parameters and authentication data to enforce resource ownership. section 11.2
- Separating complex authorization logic into a PermissionEvaluator when annotations become difficult to read. section 11.5
Authority-based protection
@PreAuthorize("hasAuthority('write')") allows Emma, who has write authority, to call getName(), while Natalie receives a 403 Forbidden response. section 11.2
Listing 11.6 The NameService class defining the protected method
@Service
public class NameService {
private Map<String, List<String>> secretNames =
Map.of(
"natalie", List.of("Energico", "Perfecto"),
"emma", List.of("Fantastico"));
@PreAuthorize #1
("#name == authentication.principal.username")
public List<String> getSecretNames(String name) {
return secretNames.get(name);
}
}
Inspect a parameter-based rule that compares the requested name with authentication.principal.username. section 11.2

