Sub topic 11
Method-level security with @PreAuthorize
This chapter assumes you can write a SecurityFilterChain bean and know how roles and authorities appear in the SecurityContext. URL rules in the filter chain protect paths. Method security protects the Java methods behind them, which helps when the rule depends on a method argument or return value.
Why add method rules
A path rule such as /api/orders/** cannot see which order owner the caller asked for. It also does not protect the service method when a scheduled job or another controller calls it. Method security runs the check at the method boundary, whichever caller reaches it.
Use both layers. Path rules give a coarse first gate. Method rules express business rules close to the code they protect.
Enabling it
Add @EnableMethodSecurity to a configuration class. Spring then wraps annotated beans in a proxy. The proxy evaluates the annotation's expression before the real method runs.
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.stereotype.Service;
@Configuration
@EnableMethodSecurity
class MethodSecurityConfig {}
record Order(String id, String owner) {}
@Service
class OrderService {
@PreAuthorize("hasRole('ADMIN') or #owner == authentication.name")
public List<Order> findOrders(String owner) {
// load and return the orders for this owner
return List.of();
}
}The expression allows admins, or a caller whose username equals the owner argument.
What you can use in an expression
| Expression | Meaning |
|---|---|
| `hasRole('ADMIN')` | Caller has the authority `ROLE_ADMIN` |
| `hasAuthority('SCOPE_orders.read')` | Caller has this exact authority |
| `authentication.name` | Name of the current principal |
| `#owner` | Value of the method parameter named `owner` |
| `isAuthenticated()` | Caller is not anonymous |
#owner works only if the compiler keeps parameter names. Spring Boot's Maven parent and Gradle plugin enable the -parameters flag. Without it, #owner is null and the check fails or behaves wrongly.
How the check runs
When the check fails, Spring throws AccessDeniedException. If the exception reaches the filter chain, ExceptionTranslationFilter turns it into 403 for an authenticated caller, or 401 for an anonymous one.
Common errors
- Self-invocation. A call from one method to another in the same class skips the proxy, so the annotation is ignored. Put secured methods in a separate bean, or call them through another bean.
- Catching the exception. A broad
@ExceptionHandler(Exception.class)in a@ControllerAdvicecan turn access denials into 500 or 200 responses. LetAccessDeniedExceptionpropagate, or handle it explicitly. - Role prefix confusion.
hasRole('ADMIN')checksROLE_ADMIN. UsehasAuthority('ADMIN')only if the authority has no prefix. - Private or final methods. Proxies cannot intercept private methods, and class-based proxies cannot override final ones. Annotate public, non-final methods.
- Quoting. Roles are string literals inside the expression, so use single quotes:
hasRole('ADMIN').
Checking the result
@PostAuthorize runs after the method and can inspect returnObject. Use it when you only know the owner after loading the data:
@PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')")
public Order findOrder(String id) {
return loadOrder(id);
}The method has already run, including any side effects. Use it only on reads.
Exercise
A service method has @PreAuthorize("hasRole('ADMIN')"). Another method in the same class calls it directly with a normal user logged in. Does the check run, and why?
Show answer
No. The call is a self-invocation, so it does not pass through the Spring proxy that evaluates the annotation. The check is skipped. Move the secured method to another bean and inject that bean.
Exercise
A request from an authenticated user fails a @PreAuthorize check. Which exception is thrown, and which status code does the client usually see?
Show answer
AccessDeniedException is thrown, and the client usually sees 403 Forbidden. An anonymous caller would see 401 instead.