Video in progress

Strong Middle 🌱 Spring

How does @PreAuthorize work, and how does it differ from URL-level checks?

With @EnableMethodSecurity on, @PreAuthorize checks a SpEL expression through a proxy before the method is called. URL rules run when the request comes in, while method security works at the business method level and can also decide based on the arguments.

📖 Answer

@Configuration
@EnableMethodSecurity
class MethodSecurityConfig { }

@Service
class OrderService {
    @PreAuthorize("hasRole('ADMIN') or #customerId == authentication.principal.id")
    public List<OrderDto> ordersOf(long customerId) { ... }

    @PostAuthorize("returnObject.ownerId == authentication.principal.id")
    public Document load(long id) { ... }
}

A URL rule (/api/admin/** hasRole ADMIN) decides who can reach which endpoint. A rule like "a user sees only their own orders" needs the argument, and that comes from method security or an explicit check in the service.

This is a proxy too, so it doesn't work on self-invocation. Cramming a complex expression into a SpEL string leads to mistakes and is hard to test, so move it into a bean: @PreAuthorize("@access.canSee(#id)"). If access is denied you get AccessDeniedException → 403. @PostAuthorize checks after the method has already run, so the method must not change anything.

On prod the most dangerous problem is IDOR: not checking that /api/orders/{id} belongs to this user. On every access by id, check the owner.