Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Authorization and Method Security

Method Security with @PreAuthorize and @PostAuthorize

Protect service methods with @EnableMethodSecurity, @PreAuthorize, @PostAuthorize and @PreFilter, and understand why it works through proxies and what self-invocation breaks.

URL rules protect doors. Method security protects the rooms behind them. A web layer rule such as /admin/** is easy to bypass by accident: a new controller path, a scheduled job, a message listener or a second entry point calling the same service. Putting the check on the service method guards the logic no matter how it is reached.

This lesson covers the annotations, how they are implemented (a proxy around your bean) and the one trap that catches almost everyone. Spring itself is not runnable on this site, so the real code is read-only; the examples that run build a tiny annotation-driven proxy in plain Java, which is exactly the mechanism Spring uses.

Switching it on

Java
@Configuration
@EnableMethodSecurity            // @PreAuthorize, @PostAuthorize, @PreFilter, @PostFilter
class MethodSecurityConfig { }

In Spring Security 6 and 7 this annotation enables the "pre/post" family by default. Other families are opt-in: jsr250Enabled = true for @RolesAllowed, securedEnabled = true for @Secured. Older code uses @EnableGlobalMethodSecurity, which is deprecated and replaced by @EnableMethodSecurity.

The four annotations

Java
@Service
class ArticleService {

    @PreAuthorize("hasAuthority('article:read')")
    public Article find(long id) { ... }

    @PreAuthorize("hasRole('EDITOR') and #article.author == authentication.name")
    public Article update(Article article) { ... }

    @PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')")
    public Document load(long id) { ... }

    @PreFilter("filterObject.owner == authentication.name")
    public void archiveAll(List<Document> docs) { ... }

    @PostFilter("filterObject.visible or hasRole('ADMIN')")
    public List<Document> search(String q) { ... }
}
Annotation Runs Typical use
@PreAuthorize Before the call Check roles, permissions and arguments (#article.author)
@PostAuthorize After the call Check the returned object (returnObject)
@PreFilter Before Remove elements from a collection argument
@PostFilter After Remove elements from a returned collection

The expressions are SpEL (the Spring Expression Language, covered in the next lesson). Inside them authentication and principal refer to the current user, #name refers to a method parameter and returnObject to the result.

When a check fails, an AccessDeniedException propagates up. An MVC controller advice or the ExceptionTranslationFilter turns it into a 403 (see exception handling).

@PostFilter is convenient but fetches everything and discards some rows afterward, which is slow and leaks counts through paging. For large data sets put the condition in the query (where owner = :me) and use @PostAuthorize only for single objects.

How it works: a proxy

Spring wraps the bean in a proxy. Callers receive the proxy; the proxy runs an interceptor (AuthorizationManagerBeforeMethodInterceptor) that evaluates the annotation and only then calls the real method. The model below does this with the JDK's own java.lang.reflect.Proxy and a custom @PreAuthorize-like annotation with a small set of conditions. Run it and watch a call be denied before the target code ever executes.

Java An annotation-driven authorization proxy (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Everything real Spring does is a more elaborate version of this: find the annotation, look up the current Authentication, evaluate an expression, either throw AccessDeniedException or proceed.

The self-invocation trap

Because the check lives in the proxy, a call that does not go through the proxy skips it. The classic case is a method calling another method of the same class:

Java
@Service
class ArticleService {

    public void publishAll(List<Long> ids) {
        ids.forEach(this::publish);          // this.publish: no proxy, no check!
    }

    @PreAuthorize("hasAuthority('article:publish')")
    public void publish(long id) { ... }
}

this is the real object, not the proxy. The annotation is silently ignored. Fixes, in order of preference:

  1. Put the annotation on the entry point (publishAll) too.
  2. Move publish into another bean and inject it.
  3. Inject the proxy of the bean into itself (works, but is a code smell).

Other things that bypass the proxy: private, final and static methods (cannot be proxied), objects created with new, and beans that are not Spring-managed. The next TryIt reproduces the trap, so you can see exactly why.

Java Self-invocation skips the check (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first call is denied, the second one returns published ids for a user without permission. A test that only calls the entry point of a class would hide this, so always test each protected method as an unauthorized user through its public entry points.

Meta-annotations and class level rules

Repeating a long expression is error-prone. Create your own annotation:

Java
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('ADMIN')")
public @interface AdminOnly { }

and use @AdminOnly anywhere. You can also put @PreAuthorize on a class; it applies to every method unless a method has its own annotation (the method one wins).

Annotate interfaces or implementations? Both work with Spring's proxies, but annotate the same place across the code base. A secure default is a class-level @PreAuthorize("denyAll()") on sensitive services plus explicit grants on the methods you intend to expose.

Method security and transactions

Order matters when both are present: authorization should run before the transaction opens, otherwise a denied request has already acquired a database connection. Spring Security's interceptor is ordered before @Transactional by default. Do not change this without a reason.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which annotation can check the object returned by a method?

    @PostAuthorize runs after the call and exposes the result as returnObject.
  2. 2. A service method calls another @PreAuthorize method of the same class with this.other(). What happens to the second annotation?

    Method security is implemented by a proxy. Calls on this do not pass through it.
  3. 3. Why is @PostFilter risky on large result sets?

    Put the restriction in the query instead and use post-checks for single objects.
  4. 4. What does @EnableMethodSecurity replace?

    The older annotation is deprecated; the new one has sensible defaults and works with the AuthorizationManager API.

Summary

  • @EnableMethodSecurity turns on @PreAuthorize, @PostAuthorize, @PreFilter and @PostFilter.
  • Checks run in a proxy around your bean; failures raise AccessDeniedException.
  • Calls through this, and private, final or static methods, bypass the check.
  • Prefer pre-checks on arguments and queries that already filter by owner; avoid post-filtering big collections.
  • Use meta-annotations for repeated rules and consider a deny-by-default class annotation.

Next: SpEL expressions and PermissionEvaluator