Spring method security: putting the permission check on the method

URL rules protect endpoints, but the same service method may also be called from a scheduled job, a message listener or another controller. Method security puts the check on the method itself, with annotations such as @PreAuthorize that Spring enforces through a proxy. This page runs each annotation, shows how rules read method arguments and return values, and demonstrates the cases where a check is silently skipped.

Contents

How method security works

Method security moves authorization from the URL to the Java method. You annotate a service method with a rule, and Spring checks it every time the method is called, whatever the caller is. A rule can also use what URL rules never see: the method's arguments, and the object it returns.

@EnableMethodSecurity registers interceptors with Spring AOP. Every bean with a security annotation is replaced by a proxy, and on each call the proxy runs this sequence:

  1. Read the Authentication of the current thread from SecurityContextHolder. With none, throw AuthenticationCredentialsNotFoundException.
  2. Evaluate the @PreAuthorize expression, a SpEL expression that can refer to authentication and to the arguments by name. If it is false, throw AuthorizationDeniedException without running the method.
  3. Run the method.
  4. Evaluate @PostAuthorize with the result available as returnObject, and apply any @PostFilter.

Because it is a proxy, method security shares every limit of Spring AOP: a call on this is not checked, and neither are private methods. The Spring AOP page explains why.

Method security annotations
AnnotationCheckedEnabled byBest for
@PreAuthorizeBefore the call, SpELDefaultMost checks: roles, authorities, rules on arguments
@PostAuthorizeAfter the call, SpEL with returnObjectDefaultOwnership of the loaded object
@PreFilter, @PostFilterEach element of a collection argument or resultDefaultRemoving elements the caller may not see or change
@AuthorizeReturnObjectProxies the returned object, so its own annotations applyDefault, since 6.3Field-level rules on domain objects
@HandleAuthorizationDeniedReplaces the exception with a valueDefault, since 6.3Masking a value instead of failing the call
@SecuredBefore the call, a list of authoritiessecuredEnabled = trueOlder code
@RolesAllowedBefore the call, JSR-250 rolesjsr250Enabled = trueCode shared with Jakarta EE

@EnableMethodSecurity arrived in Spring Security 5.6 and replaced @EnableGlobalMethodSecurity, which still exists in 7.1 but is deprecated. The new annotation turns on the pre and post annotations by default, where the old one needed prePostEnabled = true. The examples run Spring Security 7.1.2 in a plain Spring context with no web server. Each one signs a user in by putting an Authentication into SecurityContextHolder, which is what the web filter chain does for a real request.

@PreAuthorize: roles, authorities and arguments

The three methods below show the three kinds of rule people write most: a role, a fine-grained authority, and a comparison with an argument. Each is called first with nobody signed in, then by a user and by an admin, so every outcome appears:

Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

public class PreAuthorizeDemo {

    static class AccountService {
        @PreAuthorize("hasRole('ADMIN')")
        public String closeAccount(long id) {
            return "closed account " + id;
        }

        @PreAuthorize("hasAuthority('account:read')")
        public String balance(long id) {
            return "balance of " + id + " is 120";
        }

        @PreAuthorize("#owner == authentication.name or hasRole('ADMIN')")
        public String statements(String owner) {
            return "statements of " + owner;
        }
    }

    @Configuration
    @EnableMethodSecurity
    static class Config {
        @Bean
        AccountService accountService() {
            return new AccountService();
        }
    }

    static void signIn(String user, String... authorities) {
        SecurityContextHolder.getContext().setAuthentication(
                UsernamePasswordAuthenticationToken.authenticated(user, null,
                        AuthorityUtils.createAuthorityList(authorities)));
    }

    interface Call {
        String run();
    }

    static void attempt(String label, Call call) {
        try {
            System.out.println("  " + label + " -> " + call.run());
        } catch (AuthorizationDeniedException e) {
            System.out.println("  " + label + " -> " + e.getClass().getSimpleName()
                    + ": " + e.getMessage());
        } catch (AuthenticationCredentialsNotFoundException e) {
            System.out.println("  " + label + " -> " + e.getClass().getSimpleName());
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            AccountService accounts = context.getBean(AccountService.class);

            System.out.println("No one signed in:");
            attempt("balance(7)", () -> accounts.balance(7));

            signIn("ann", "ROLE_USER", "account:read");
            System.out.println("ann, authorities [ROLE_USER, account:read]:");
            attempt("balance(7)", () -> accounts.balance(7));
            attempt("statements(\"ann\")", () -> accounts.statements("ann"));
            attempt("statements(\"bob\")", () -> accounts.statements("bob"));
            attempt("closeAccount(7)", () -> accounts.closeAccount(7));

            signIn("root", "ROLE_ADMIN");
            System.out.println("root, authorities [ROLE_ADMIN]:");
            attempt("statements(\"bob\")", () -> accounts.statements("bob"));
            attempt("closeAccount(7)", () -> accounts.closeAccount(7));
            attempt("balance(7)", () -> accounts.balance(7));
        }
    }
}
Output
No one signed in:
  balance(7) -> AuthenticationCredentialsNotFoundException
ann, authorities [ROLE_USER, account:read]:
  balance(7) -> balance of 7 is 120
  statements("ann") -> statements of ann
  statements("bob") -> AuthorizationDeniedException: Access Denied
  closeAccount(7) -> AuthorizationDeniedException: Access Denied
root, authorities [ROLE_ADMIN]:
  statements("bob") -> statements of bob
  closeAccount(7) -> closed account 7
  balance(7) -> AuthorizationDeniedException: Access Denied
  • With nobody signed in, balance(7) threw AuthenticationCredentialsNotFoundException, not a denial: there was no user to check. In a web application the filter chain normally prevents this case by putting an anonymous user in the context.
  • ann could read balances, because she has the authority account:read, and her own statements, because #owner == authentication.name compared the argument "ann" with her name.
  • For statements("bob") and closeAccount(7), ann got AuthorizationDeniedException: Access Denied, and the methods never ran.
  • root could read bob's statements and close the account through hasRole('ADMIN'), but was refused balance(7): the role ADMIN does not include the authority account:read. Roles and authorities are just strings, and nothing makes one imply another unless you configure a RoleHierarchy bean.

#owner refers to the parameter by name, which works only when the class is compiled with javac -parameters. Spring Boot's build plugins do that by default; elsewhere, add the flag or name parameters with @P("owner"). AuthorizationDeniedException, added in 6.3, extends AccessDeniedException, so code that catches the older exception still works, and in a web request ExceptionTranslationFilter turns either into a 403.

@PostAuthorize: checking what the method returned

Some rules depend on data you only have after loading it, such as the owner of a document. @PostAuthorize runs the method first and checks the result. Here ann opens her own document and then someone else's, and the method records each opening, so the side effect is visible:

Java
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

public class PostAuthorizeDemo {

    record Document(long id, String owner, String title) {
    }

    static class DocumentService {
        final List<String> auditLog = new ArrayList<>();

        @PostAuthorize("returnObject.owner == authentication.name")
        public Document open(long id) {
            Document doc = id == 1 ? new Document(1, "ann", "Ann's tax return")
                                   : new Document(2, "bob", "Bob's payslip");
            auditLog.add("opened " + id + " (marked as read)");   // side effect
            return doc;
        }

        public List<String> auditLog() {
            return auditLog;
        }
    }

    @Configuration
    @EnableMethodSecurity
    static class Config {
        @Bean
        DocumentService documentService() {
            return new DocumentService();
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            DocumentService docs = context.getBean(DocumentService.class);
            SecurityContextHolder.getContext().setAuthentication(
                    UsernamePasswordAuthenticationToken.authenticated("ann", null,
                            AuthorityUtils.createAuthorityList("ROLE_USER")));
            for (long id : new long[] {1, 2}) {
                try {
                    System.out.println("open(" + id + ") -> " + docs.open(id));
                } catch (AuthorizationDeniedException e) {
                    System.out.println("open(" + id + ") -> " + e.getMessage());
                }
            }
            System.out.println("audit log: " + docs.auditLog());
        }
    }
}
Output
open(1) -> Document[id=1, owner=ann, title=Ann's tax return]
open(2) -> Access Denied
audit log: [opened 1 (marked as read), opened 2 (marked as read)]
  • Document 1 belongs to ann, so returnObject.owner == authentication.name was true and she received it.
  • Document 2 belongs to bob. The method ran, loaded it, and only then was the result refused with Access Denied.
  • The audit log has two entries. The denied call still marked document 2 as read, because a post check cannot undo what the method already did.

Use @PostAuthorize only on methods that read. For anything that writes, check permission before the change, either with @PreAuthorize and a lookup of the owner, or with a custom bean as in the section after next. If the method is @Transactional and the denial must roll back its writes, make sure the security interceptor runs inside the transaction; by default it does not.

@PreFilter and @PostFilter: filtering collections

Filtering annotations evaluate an expression for each element of a collection, with the element as filterObject, and remove the elements for which it is false. The invoice service returns 1,000 invoices, of which 4 belong to ann, to make the cost visible:

Java
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

public class FilterDemo {

    record Invoice(int id, String owner) {
    }

    static class InvoiceService {
        int rowsLoaded;

        @PostFilter("filterObject.owner == authentication.name")
        public List<Invoice> all() {
            List<Invoice> rows = new ArrayList<>();
            for (int i = 1; i <= 1000; i++) {
                rows.add(new Invoice(i, i % 250 == 0 ? "ann" : "someone-else"));
            }
            rowsLoaded += rows.size();
            return rows;
        }

        public int rowsLoaded() {
            return rowsLoaded;
        }

        @PostFilter("filterObject.owner == authentication.name")
        public List<Invoice> immutable() {
            return List.of(new Invoice(1, "ann"), new Invoice(2, "bob"));
        }

        @PreFilter("filterObject.owner == authentication.name")
        public String deleteAll(List<Invoice> invoices) {
            return "deleting " + invoices;
        }
    }

    @Configuration
    @EnableMethodSecurity
    static class Config {
        @Bean
        InvoiceService invoiceService() {
            return new InvoiceService();
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            InvoiceService service = context.getBean(InvoiceService.class);
            SecurityContextHolder.getContext().setAuthentication(
                    UsernamePasswordAuthenticationToken.authenticated("ann", null,
                            AuthorityUtils.createAuthorityList("ROLE_USER")));

            List<Invoice> mine = service.all();
            System.out.println("@PostFilter: loaded " + service.rowsLoaded()
                    + " rows, returned " + mine.size() + ": " + mine);

            List<Invoice> request = new ArrayList<>(List.of(new Invoice(4, "ann"),
                    new Invoice(5, "bob"), new Invoice(6, "ann")));
            System.out.println("@PreFilter: " + service.deleteAll(request));
            System.out.println("caller's list afterwards: " + request);

            List<Invoice> fromImmutable = service.immutable();
            System.out.println("@PostFilter on List.of(...): " + fromImmutable + ", a "
                    + fromImmutable.getClass().getSimpleName());
        }
    }
}
Output
@PostFilter: loaded 1000 rows, returned 4: [Invoice[id=250, owner=ann], Invoice[id=500, owner=ann], Invoice[id=750, owner=ann], Invoice[id=1000, owner=ann]]
@PreFilter: deleting [Invoice[id=4, owner=ann], Invoice[id=6, owner=ann]]
caller's list afterwards: [Invoice[id=4, owner=ann], Invoice[id=6, owner=ann]]
@PostFilter on List.of(...): [Invoice[id=1, owner=ann]], a ArrayList
  • @PostFilter returned only ann's invoices 250, 500, 750 and 1000, but the method loaded all 1,000 rows first. The filtering happens in memory, after the database has done all the work.
  • @PreFilter removed bob's invoice 5 from the argument before the method saw it, so only 4 and 6 were deleted.
  • The caller's own list also lost invoice 5. @PreFilter changes the collection that was passed in, which surprises callers that use the list again afterwards.
  • @PostFilter on an immutable List.of(...) worked and returned a new ArrayList, so you do not have to return a mutable list.

The filters are convenient for small lists, but for anything that can grow, filter in the query instead, for example with a WHERE owner = ? clause or a Spring Data method such as findByOwner. Pagination makes in-memory filtering wrong as well as slow: filtering a page of 20 rows can leave 3, and the next page is computed without knowing that.

Custom rules: beans in expressions and meta-annotations

Expressions grow hard to read once a rule needs data, such as who owns a project. Two features keep annotations short: calling a Spring bean from the expression with @beanName, and defining your own annotation with a template. This program uses both:

Java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AnnotationTemplateExpressionDefaults;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

public class CustomExpressions {

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @PreAuthorize("hasAnyRole({roles})")
    @interface AllowRoles {
        String[] roles();
    }

    static class ProjectAccess {
        private final Map<Long, String> owners = Map.of(10L, "ann", 20L, "bob");

        public boolean canEdit(long projectId, Authentication auth) {
            System.out.println("    projectAccess.canEdit(" + projectId + ", " + auth.getName()
                    + ")");
            return auth.getName().equals(owners.get(projectId));
        }
    }

    static class ProjectService {
        @PreAuthorize("@projectAccess.canEdit(#projectId, authentication)")
        public String rename(long projectId, String name) {
            return "project " + projectId + " renamed to " + name;
        }

        @AllowRoles(roles = {"'MANAGER'", "'ADMIN'"})
        public String budget(long projectId) {
            return "budget of " + projectId + " is 5000";
        }
    }

    @Configuration
    @EnableMethodSecurity
    static class Config {
        @Bean
        static AnnotationTemplateExpressionDefaults templateDefaults() {
            return new AnnotationTemplateExpressionDefaults();
        }

        @Bean
        ProjectAccess projectAccess() {
            return new ProjectAccess();
        }

        @Bean
        ProjectService projectService() {
            return new ProjectService();
        }
    }

    interface Call {
        String run();
    }

    static void attempt(String label, Call call) {
        System.out.println("  " + label);
        try {
            System.out.println("    -> " + call.run());
        } catch (AuthorizationDeniedException e) {
            System.out.println("    -> " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            ProjectService projects = context.getBean(ProjectService.class);
            SecurityContextHolder.getContext().setAuthentication(
                    UsernamePasswordAuthenticationToken.authenticated("ann", null,
                            AuthorityUtils.createAuthorityList("ROLE_MANAGER")));
            System.out.println("ann, ROLE_MANAGER:");
            attempt("rename(10, \"Apollo\")", () -> projects.rename(10, "Apollo"));
            attempt("rename(20, \"Gemini\")", () -> projects.rename(20, "Gemini"));
            attempt("budget(10)", () -> projects.budget(10));

            SecurityContextHolder.getContext().setAuthentication(
                    UsernamePasswordAuthenticationToken.authenticated("bob", null,
                            AuthorityUtils.createAuthorityList("ROLE_USER")));
            System.out.println("bob, ROLE_USER:");
            attempt("budget(10)", () -> projects.budget(10));
        }
    }
}
Output
ann, ROLE_MANAGER:
  rename(10, "Apollo")
    projectAccess.canEdit(10, ann)
    -> project 10 renamed to Apollo
  rename(20, "Gemini")
    projectAccess.canEdit(20, ann)
    -> Access Denied
  budget(10)
    -> budget of 10 is 5000
bob, ROLE_USER:
  budget(10)
    -> Access Denied
  • @projectAccess.canEdit(#projectId, authentication) called the bean named projectAccess, and its print line shows the arguments it received. It returned true for project 10, owned by ann, and false for project 20, owned by bob.
  • @AllowRoles(roles = {"'MANAGER'", "'ADMIN'"}) expanded to hasAnyRole('MANAGER', 'ADMIN'), so ann, a manager, could read the budget and bob, a plain user, could not.

A bean method is ordinary Java: it can be unit tested, use a repository, and be reused from many annotations. It is usually the clearest way to write ownership rules. Templates in meta-annotations, such as {roles}, need an AnnotationTemplateExpressionDefaults bean, available since Spring Security 6.4; declare it static, because it must exist before the method security infrastructure is created. Without templates, a meta-annotation can still carry a fixed expression, such as an @IsAdmin annotation marked with @PreAuthorize("hasRole('ADMIN')"). For permissions stored per object in database tables, see Spring Security ACLs.

Masking instead of failing: @HandleAuthorizationDenied

Sometimes a denial should not fail the whole call: a support agent may see a customer record but not the email address. Spring Security 6.3 added two annotations for this. @AuthorizeReturnObject wraps the returned object in a proxy so that its own annotations are enforced, and @HandleAuthorizationDenied replaces a denial with a value:

Java
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authorization.AuthorizationResult;
import org.springframework.security.authorization.method.AuthorizeReturnObject;
import org.springframework.security.authorization.method.HandleAuthorizationDenied;
import org.springframework.security.authorization.method.MethodAuthorizationDeniedHandler;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

public class DeniedHandling {

    public static class Mask implements MethodAuthorizationDeniedHandler {
        @Override
        public Object handleDeniedInvocation(MethodInvocation invocation,
                                             AuthorizationResult result) {
            return "****";
        }
    }

    public static class Customer {
        private final String name;
        private final String email;

        public Customer(String name, String email) {
            this.name = name;
            this.email = email;
        }

        public String getName() {
            return name;
        }

        @PreAuthorize("hasAuthority('customer:pii')")
        @HandleAuthorizationDenied(handlerClass = Mask.class)
        public String getEmail() {
            return email;
        }
    }

    static class CustomerService {
        @AuthorizeReturnObject
        public Customer find(long id) {
            return new Customer("Ann Lee", "ann@example.com");
        }
    }

    @Configuration
    @EnableMethodSecurity
    static class Config {
        @Bean
        Mask mask() {
            return new Mask();
        }

        @Bean
        CustomerService customerService() {
            return new CustomerService();
        }
    }

    static void show(CustomerService service, String user, String... authorities) {
        SecurityContextHolder.getContext().setAuthentication(
                UsernamePasswordAuthenticationToken.authenticated(user, null,
                        AuthorityUtils.createAuthorityList(authorities)));
        Customer c = service.find(1);
        System.out.println(user + ": name = " + c.getName() + ", email = " + c.getEmail());
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            CustomerService service = context.getBean(CustomerService.class);
            show(service, "support", "ROLE_SUPPORT");
            show(service, "dpo", "ROLE_SUPPORT", "customer:pii");
            System.out.println("returned object class: "
                    + service.find(1).getClass().getSimpleName());
        }
    }
}
Output
support: name = Ann Lee, email = ****
dpo: name = Ann Lee, email = ann@example.com
returned object class: DeniedHandling$Customer$$SpringCGLIB$$0
  • For support, getName() returned Ann Lee, and getEmail() returned ****. The @PreAuthorize on the getter failed, and the Mask handler supplied a value instead of an exception.
  • For dpo, who has the authority customer:pii, the real email came back.
  • The returned object's class is Customer$$SpringCGLIB$$0: find returned a proxy around the Customer, which is how annotations on a plain domain object take effect.

The proxy needs a class it can subclass, so the domain class must not be final, which rules out records. When the returned object is serialised to JSON, the masked values appear in the response, which is often exactly what an API needs. The handler class is looked up as a bean, so it can be configured like any other.

Checks that silently do nothing

A missing check does not fail; it just lets the call through. This program runs the same calls under two configurations to show the two most common ways a rule is ignored:

Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

public class MethodSecurityTraps {

    static class AdminService {
        public String dashboard() {
            return "dashboard, then " + this.purgeCache();   // call on 'this'
        }

        @PreAuthorize("hasRole('ADMIN')")
        public String purgeCache() {
            return "cache purged";
        }

        @Secured("ROLE_ADMIN")
        public String legacyPurge() {
            return "legacy purge ran";
        }
    }

    @Configuration
    @EnableMethodSecurity                       // securedEnabled is false by default
    static class Defaults {
        @Bean
        AdminService adminService() {
            return new AdminService();
        }
    }

    @Configuration
    @EnableMethodSecurity(securedEnabled = true)
    static class WithSecured {
        @Bean
        AdminService adminService() {
            return new AdminService();
        }
    }

    interface Call {
        String run();
    }

    static void attempt(String label, Call call) {
        try {
            System.out.println("  " + label + " -> " + call.run());
        } catch (AuthorizationDeniedException e) {
            System.out.println("  " + label + " -> denied");
        }
    }

    public static void main(String[] args) {
        SecurityContextHolder.getContext().setAuthentication(
                UsernamePasswordAuthenticationToken.authenticated("ann", null,
                        AuthorityUtils.createAuthorityList("ROLE_USER")));
        for (Class<?> config : new Class<?>[] {Defaults.class, WithSecured.class}) {
            System.out.println("ann (ROLE_USER), config " + config.getSimpleName() + ":");
            try (var context = new AnnotationConfigApplicationContext(config)) {
                AdminService admin = context.getBean(AdminService.class);
                attempt("purgeCache()", admin::purgeCache);
                attempt("dashboard()", admin::dashboard);
                attempt("legacyPurge()", admin::legacyPurge);
            }
        }
    }
}
Output
ann (ROLE_USER), config Defaults:
  purgeCache() -> denied
  dashboard() -> dashboard, then cache purged
  legacyPurge() -> legacy purge ran
ann (ROLE_USER), config WithSecured:
  purgeCache() -> denied
  dashboard() -> dashboard, then cache purged
  legacyPurge() -> denied
  • Called directly, purgeCache() was denied to ann in both configurations.
  • Called from dashboard() on the same bean, it ran: the output reads dashboard, then cache purged. The internal call on this went to the target object, not through the proxy, so the rule was never evaluated. A rule on a method that is also called from inside its class protects only the outside entrance.
  • With the default @EnableMethodSecurity, legacyPurge(), marked @Secured("ROLE_ADMIN"), ran for a plain user. @Secured is off unless securedEnabled = true, and an annotation nobody reads changes nothing.
  • With securedEnabled = true, the same call was denied.

Other ways a rule is skipped:

  • Private and final methods: the proxy cannot intercept them, so their annotations are ignored.
  • Objects created with new: only Spring beans get a proxy.
  • Other threads: @Async methods and executors run without the caller's security context unless it is propagated, as the Spring Security page shows with DelegatingSecurityContextExecutorService.

Write a test for each important rule that calls the method as a user who must be refused. spring-security-test provides @WithMockUser(roles = "USER") to set up the context in a test, so these tests need no login code.

Choosing between URL rules and method rules

Where each kind of check fits
RuleBest place
Whole areas of the application: /admin/** for admins onlyURL rules in the SecurityFilterChain
A role or authority for one operation@PreAuthorize("hasAuthority('orders:refund')")
A rule that compares an argument with the user@PreAuthorize("#owner == authentication.name")
Ownership that needs a database lookupA bean method called from @PreAuthorize
Ownership of the loaded object, for read-only methods@PostAuthorize
Hiding rows the user may not seeA filter in the query; @PostFilter only for small lists
Hiding single fields@AuthorizeReturnObject with @HandleAuthorizationDenied
Permissions granted per object and stored in tablesSpring Security ACL
The same rule used in many placesA meta-annotation such as @IsAdmin or a template annotation

Most applications use both kinds: coarse URL rules as the outer wall, and method rules for anything that depends on the data. For OAuth2 scopes in method rules, such as hasAuthority('SCOPE_orders.read'), see the OAuth2 resource server page; for WebFlux, where method security works on Mono and Flux, see reactive security.