Sub topic 11
Method-level security with @PreAuthorize
This chapter assumes you can already write a SecurityFilterChain bean and know how roles and authorities end up in the SecurityContext. It also assumes you are comfortable with Spring beans and annotations. URL rules decide who may reach an endpoint. Method security decides who may run a particular piece of code, wherever it is called from.
Why add method security
The authorizeHttpRequests rules in the filter chain match request paths. That works well for coarse rules such as "everything under /api/admin/ needs ADMIN". It has three limits:
- A rule can only see the request: the path, the HTTP method and the caller. It cannot see the arguments your code ends up using, or the object your code returns.
- The same service method may be reached from a controller, a scheduled job, or a message listener. Only a rule on the method covers all of those callers.
- Path patterns can drift out of sync with controller mappings, so a new endpoint can end up unprotected.
Method security puts the rule next to the code it protects. A common approach is to keep broad rules in the filter chain and put business rules, such as "only the owner of an order", on service methods.
Enabling method security
Add @EnableMethodSecurity to a configuration class. In Spring Security 6 it turns on @PreAuthorize, @PostAuthorize, @PreFilter and @PostFilter by default. It replaces the older @EnableGlobalMethodSecurity, which is deprecated.
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.stereotype.Service;
@Configuration
@EnableMethodSecurity
class MethodSecurityConfig {}
record Order(long id, String owner) {}
@Service
class OrderService {
@PreAuthorize("hasRole('ADMIN') or #owner == authentication.name")
public List<Order> findOrders(String owner) {
// load and return the orders for this owner
return List.of();
}
@PostAuthorize("hasRole('ADMIN') or returnObject.owner() == authentication.name")
public Order findById(long id) {
return new Order(id, "alice");
}
}@PreAuthorize runs before the method body. If the expression is false, the method never executes. @PostAuthorize runs the method first and then checks the result, which is useful when the rule depends on data you only have after loading it.
Writing the expressions
The annotation value is a Spring Expression Language (SpEL) string. These names are available in it:
| Expression | Meaning |
|---|---|
| `hasRole('ADMIN')` | The user has the authority `ROLE_ADMIN`. Spring adds the `ROLE_` prefix for you. |
| `hasAnyRole('USER', 'ADMIN')` | The user has at least one of the roles. |
| `hasAuthority('SCOPE_orders.read')` | The user has exactly this authority string, with no prefix added. |
| `authentication` | The current `Authentication` object. |
| `principal` | The principal inside it, such as a `UserDetails` or a `Jwt`. |
| `#owner` | The method argument named `owner`. |
| `returnObject` | The returned value. Only available in `@PostAuthorize`. |
| `permitAll()`, `denyAll()`, `isAuthenticated()` | Fixed outcomes or a login check. |
With a JWT resource server, scopes become SCOPE_ authorities. Use hasAuthority('SCOPE_orders.read') for them, because hasRole('orders.read') looks for ROLE_orders.read and never matches.
Argument names must be discoverable
#owner only works if Spring can read the parameter name at runtime. Spring Boot's Maven and Gradle plugins compile with the -parameters flag, so this normally works. If you compile with a custom setup and the name is missing, the expression fails or evaluates to null. You can state the name explicitly with @P:
import org.springframework.security.access.method.P;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
class ReportService {
@PreAuthorize("#owner == authentication.name")
public String report(@P("owner") String owner) {
return "report for " + owner;
}
}Calling a bean from an expression
Long expressions are hard to read and hard to test. Move the logic into a bean and call it with @:
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
@Component("orderAccess")
class OrderAccess {
boolean canView(long orderId, Authentication authentication) {
// look up the order and compare its owner with authentication.getName()
return authentication.isAuthenticated();
}
}You then write @PreAuthorize("@orderAccess.canView(#id, authentication)"). The bean is a plain class, so you can unit test it without a Spring context.
Reusable annotations
You can wrap an expression in your own annotation. This keeps the rule in one place:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.access.prepost.PreAuthorize;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('ADMIN')")
public @interface IsAdmin {}How it works internally
Spring wraps each secured bean in a proxy. A call from another bean goes to the proxy first. The proxy evaluates the expression against the current SecurityContext and either forwards the call or throws.
Because the proxy is the enforcement point, a few cases silently skip the check:
- Self-invocation. If
findOrderscalls another method onthis, that inner call does not pass through the proxy, so the inner annotation is ignored. - Non-proxyable methods.
privateandfinalmethods, and methods onfinalclasses, cannot be intercepted by the default proxying. - Objects you create yourself. An instance made with
newis not a Spring bean and has no proxy.
Put annotations on public methods of Spring-managed beans, and call them from other beans.
What the caller sees on failure
A failed check throws AccessDeniedException. When the call came from a controller, the exception travels up to the ExceptionTranslationFilter in the security filter chain. It answers 403 for an authenticated user and starts the authentication entry point, giving 401, for an anonymous one. This is the same handling as for URL rules, so any custom handlers you configure also apply here.
One common trap: a @ControllerAdvice with a catch-all @ExceptionHandler(Exception.class) also catches AccessDeniedException. The client then gets whatever status your handler picks, often 500. Either add a more specific handler that rethrows or maps AccessDeniedException to 403, or exclude it from the catch-all.
Filtering collections
@PostFilter removes elements from a returned collection that fail an expression. @PreFilter does the same for a collection argument. Inside the expression, filterObject is the current element.
import java.util.List;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.stereotype.Service;
@Service
class ArchiveService {
@PostFilter("filterObject.owner() == authentication.name or hasRole('ADMIN')")
public List<Order> all() {
return List.of(new Order(1, "alice"), new Order(2, "bob"));
}
}This loads every element and filters in memory. For large tables it is better to pass the owner into the query, and use @PreAuthorize to check that the caller may ask for that owner.
Testing method security
You can test a secured service without HTTP. Load only the configuration and the service, then use @WithMockUser to set the SecurityContext. This needs spring-boot-starter-test and spring-security-test.
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
@SpringBootTest(classes = {MethodSecurityConfig.class, OrderService.class})
class OrderServiceSecurityTest {
@Autowired
OrderService service;
@Test
@WithMockUser(username = "alice", roles = "USER")
void ownerCanReadOwnOrders() {
assertThat(service.findOrders("alice")).isEmpty();
}
@Test
@WithMockUser(username = "alice", roles = "USER")
void otherUsersOrdersAreDenied() {
assertThatThrownBy(() -> service.findOrders("bob"))
.isInstanceOf(AccessDeniedException.class);
}
@Test
@WithMockUser(username = "root", roles = "ADMIN")
void adminCanReadAnyOrders() {
assertThat(service.findOrders("bob")).isEmpty();
}
}The tests call the injected bean, which is the proxy. If you instantiated OrderService with new, all three tests would pass for the wrong reason, because no check would run and the denial test would fail.
Common mistakes
- Using
hasRole('ROLE_ADMIN'). Spring Security 6 accepts it, but the prefix is redundant. UsehasRole('ADMIN'). - Using
hasRolefor JWT scopes instead ofhasAuthority('SCOPE_...'). - Forgetting
@EnableMethodSecurity. The annotations then do nothing, and no error appears. - Annotating a private or self-invoked method.
- Comparing
#owner == principalwhen the principal is aUserDetailsobject. Useauthentication.name, orprincipal.username.
Exercise
A service method is annotated with @PreAuthorize("hasRole('ADMIN')"). Another method in the same class calls it as this.deleteAll(). A non-admin user triggers the outer method, and deleteAll() runs. Why did the check not fire, and how would you fix it?
Show answer
The check is enforced by a proxy around the bean. A call on this goes straight to the real object and skips the proxy, so the annotation is never evaluated. Fix it by moving deleteAll() into a separate Spring bean and injecting that bean, so the call passes through its proxy. Alternatively, put the same @PreAuthorize on the outer method that is called from outside.
Exercise
Write a @PreAuthorize expression that lets a caller run readOrders() if their JWT has the scope orders.read, or if they have the role ADMIN.
Show answer
@PreAuthorize("hasAuthority('SCOPE_orders.read') or hasRole('ADMIN')"). Spring derives the SCOPE_orders.read authority from the token's scope claim, and hasRole('ADMIN') checks for ROLE_ADMIN.