Quick revision
The short answer
We add @EnableMethodSecurity to a configuration class, which turns on @PreAuthorize and @PostAuthorize by default, and annotate the method with @PreAuthorize("hasRole('SUPPORT') or #customerId == authentication.name"). The expression is evaluated by a proxy just before the method body runs, using the actual argument values; @PostAuthorize would run after the method and can inspect returnObject. Because it is proxy-based, a call from another method of the same class skips the check.
What to remember
In this answer, we enabled method security with @EnableMethodSecurity, wrote a @PreAuthorize expression that allows support staff or the customer themselves, and saw that the proxy evaluates it just before the method body with the real arguments. We compared it with @PostAuthorize, which checks returnObject after the method runs, saw how -parameters or @P make parameter names available, and saw why self-invocation and private methods bypass the check.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We add @EnableMethodSecurity to a configuration class, which turns on @PreAuthorize and @PostAuthorize by default, and annotate the method with @PreAuthorize("hasRole('SUPPORT') or #customerId == authentication.name"). The expression is evaluated by a proxy just before the method body runs, using the actual argument values; @PostAuthorize would run after the method and can inspect returnObject. Because it is proxy-based, a call from another method of the same class skips the check.
Why this question is asked
URL rules can say that /orders requires a login, but they cannot easily say that a customer may read only their own orders. That kind of rule depends on method arguments, and method security is Spring's tool for it. Interviewers ask this coding question to see whether we can write the expression correctly and, more importantly, whether we understand when and how it runs, because most method security bugs come from that misunderstanding. In this answer, we will enable method security, write the method, follow the call through the proxy, compare @PreAuthorize with @PostAuthorize, see how parameter names reach the expression, and look at the self-invocation trap.
1Enabling Method Security
Method security is off until we enable it. In Spring Security 6 and later, the annotation is @EnableMethodSecurity, which replaced the older @EnableGlobalMethodSecurity. Its prePostEnabled attribute is true by default, so @PreAuthorize and @PostAuthorize work without further settings. @Secured and the JSR-250 annotations such as @RolesAllowed stay off unless we ask for them.
Notice that one annotation anywhere in the application context is enough. In Spring Boot, putting it on the main security configuration class is the usual choice, so readers find it next to the URL rules.
2Writing the Method
Here is the service method. Customers are identified by their username, which is also their customer id in this example, and support staff have the role SUPPORT.
The expression is Spring Expression Language (SpEL). hasRole('SUPPORT') checks for the authority ROLE_SUPPORT. #customerId refers to the method parameter of that name, and authentication is the current Authentication object from the security context, whose getName() returns the username. The or means support staff pass on the first part, and everyone else passes only when the requested id is their own.
When the check fails, Spring Security throws an AccessDeniedException (in recent versions the subclass AuthorizationDeniedException). Called from a controller, it becomes a 403 response through the normal exception handling.
3When Is the Expression Evaluated?
Spring does not change our class. At startup it sees the annotation and wraps the bean in a proxy, a generated object that has the same methods and sits between callers and our real object. Other beans are given the proxy. When a controller calls findOrders("bob"), the proxy's method security interceptor runs first: it builds an evaluation context with the arguments and the current Authentication, evaluates the expression, and only if the result is true calls the real method.
5 messages in order. Play them, or step through them one at a time.
For an allowed call, the interceptor passes the call on to the real OrderService instead.
So the timing is: after Spring MVC has bound the arguments, before a single line of our method runs. That is why @PreAuthorize is the right choice here: a denied request costs no database query and has no side effects.
4@PostAuthorize and returnObject
Sometimes we cannot decide before running the method, because the rule depends on what is loaded. @PostAuthorize runs the method first and then evaluates the expression with the result available as returnObject.
Notice the cost. The query has already run, and if the method had changed data, that change would already have happened. So @PostAuthorize suits read-only methods. For lists, @PostFilter removes elements the user may not see, but it filters in memory after loading everything, so for large results a query filtered by customer is better.
5How #customerId Finds the Parameter Name
Java bytecode does not keep parameter names unless the compiler is told to. With the -parameters flag, javac stores them, and Spring reads them through reflection. Spring Boot's Maven parent and Gradle plugin configure -parameters for us, which is why #customerId just works in a Boot project. Since Spring Framework 6.1, Spring no longer falls back to reading debug information, so a project built without Boot's build setup can find the name missing and the expression fails.
If we cannot control the compiler flags, we name the parameter explicitly with Spring Security's @P annotation, or Spring Data's @Param, which method security also understands.
Either way, a quick test that calls the method as a non-support user with someone else's id is the best proof that the name resolves.
6The Self-Invocation Trap
Because the check lives in the proxy, it only runs when the call passes through the proxy. A call from inside the same class uses this, the real object, and skips it.
The fix is to put the annotation on the public entry point that callers use (summary here), or to move the protected method into another bean so the call crosses a proxy. The same rule means private and final methods cannot be secured this way, since the proxy cannot override them.
7Follow-up questions
Why use authentication.name instead of a principal property?
authentication.name works for every kind of authentication: form login, JWT (where it is the sub claim by default) and others. Expressions like principal.customerId depend on a custom principal class and break when the authentication type changes.
Can I move the expression out of the annotation?
Yes, and for complex rules we should. We write a bean such as orderAccess with a method canRead(Authentication, String) and call it with @PreAuthorize("@orderAccess.canRead(authentication, #customerId)"). The logic is then plain Java that we can unit test.
Does method security work on reactive methods?
Yes, with @EnableReactiveMethodSecurity for methods returning Mono or Flux. The check then happens when the publisher is subscribed, not when the method is called.
8Conclusion
In this answer, we enabled method security with @EnableMethodSecurity, wrote a @PreAuthorize expression that allows support staff or the customer themselves, and saw that the proxy evaluates it just before the method body with the real arguments. We compared it with @PostAuthorize, which checks returnObject after the method runs, saw how -parameters or @P make parameter names available, and saw why self-invocation and private methods bypass the check.
Open with
I would add @EnableMethodSecurity to a configuration class, which replaced @EnableGlobalMethodSecurity and enables pre and post annotations by default. Then on the service method findOrders(String customerId) I put @PreAuthorize with the expression hasRole('SUPPORT') or #customerId == authentication.name. hasRole checks for ROLE_SUPPORT, #customerId reads the method argument, and authentication.name is the current user's name.
Then, if they want more
As for timing: Spring wraps the bean in a proxy, and when a caller invokes the method, the interceptor evaluates the expression after the arguments are known but before the method body runs, so a denied call throws AccessDeniedException and never touches the database. @PostAuthorize is the other option: it runs the method first and then evaluates with returnObject, which is useful when the rule depends on the loaded data, but the work has already been done, so I keep it for read-only methods.
Parameter names are available because Spring Boot compiles with -parameters; otherwise I would use @P to name the argument. Finally, because it is proxy-based, calling findOrders from another method in the same class skips the check, so the annotation belongs on the entry point callers actually use.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 6, Spring Security 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Security reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Enable method security in a Spring Boot 3 or 4 service and write a method that only...": https://scrivio-interview-library.netlify.app/spring-boot/authorization/53ad2b366e/