Method security with @PreAuthorize

Spring Security · lesson 9 of 31 · 3 min read

Enforce rules on service methods, not just URLs, and avoid the proxy traps that silently skip them.

Open this lesson in the learning hub

Key points

  • URL rules guard HTTP. Method security guards the method, so the rule holds however the call arrives.
  • Enable it with @EnableMethodSecurity. @PreAuthorize and @PostAuthorize work out of the box.
  • The older @EnableGlobalMethodSecurity is deprecated — do not reach for it in new code.
  • The expression is SpEL. Method arguments (#post), authentication and principal are all in scope.
  • It runs through a proxy. A call from inside the same bean, or on a private method, is not checked.
  • @PostAuthorize evaluates 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.