Method security with @PreAuthorize
Enforce rules on service methods, not just URLs, and avoid the proxy traps that silently skip them.
Open this lesson in the learning hubKey points
- URL rules guard HTTP. Method security guards the method, so the rule holds however the call arrives.
- Enable it with
@EnableMethodSecurity.@PreAuthorizeand@PostAuthorizework out of the box. - The older
@EnableGlobalMethodSecurityis deprecated — do not reach for it in new code. - The expression is SpEL. Method arguments (
#post),authenticationandprincipalare all in scope. - It runs through a proxy. A call from inside the same bean, or on a private method, is not checked.
@PostAuthorizeevaluates after the method returns — perfect for ownership checks, wasteful if the work is expensive.
Example
@Configuration
@EnableMethodSecurity
class MethodSecurityConfig { }
@Service
public class PostService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteAny(Long id) { ... }
@PreAuthorize("hasAuthority('post:edit') and #post.authorEmail == authentication.name")
public Post update(Post post) { ... }
@PostAuthorize("returnObject.authorEmail == authentication.name")
public Post findDraft(Long id) { ... }
}
Guard the service method, not only the URL — but remember self-calls bypass the proxy.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.