Spring Security: @PreAuthorize secures a method, not a URL

Useful when the rule depends on the arguments rather than the path.

Code
@EnableMethodSecurity
@Configuration
class SecurityConfig { }

@Service
class OrderService {

    @PreAuthorize("hasRole('ADMIN') or #username == authentication.name")
    public List<Order> ordersOf(String username) { ... }

    @PostAuthorize("returnObject.owner == authentication.name")
    public Order byId(Long id) { ... }
}
Output
An admin sees anyone's orders.
A user sees only their own - enforced in one line, next to the method it protects.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11