Sub topic 11
Fine-grained checks with @PreAuthorize
Request rules in the SecurityFilterChain decide access by URL and HTTP method. They can't see the method arguments, the loaded domain object, or the result. This chapter adds method security, which runs checks inside the call, at the method boundary. It assumes you have the resource server from the previous chapters, including a JwtAuthenticationConverter or the default SCOPE_ mapping, and that you know basic SpEL (Spring Expression Language) syntax.
Why URL rules are not enough
A rule such as .requestMatchers("/orders/**").authenticated() cannot express "a user may read only their own order". The decision depends on data that exists after the request is routed: a path variable, a database row, a claim in the token. Method security fills that gap. It also protects the service layer when the same method is reached from a scheduled job, a message listener, or another controller.
Use both layers. Request rules reject obviously wrong callers early. Method annotations enforce business rules next to the code they protect.
How method security works
@EnableMethodSecurity registers interceptors around beans that carry security annotations. When a caller invokes an annotated method on the Spring proxy, the interceptor reads the current Authentication from the SecurityContext. It evaluates the SpEL expression and either proceeds or throws AccessDeniedException.
In Spring Security 6 and later, @EnableMethodSecurity turns on @PreAuthorize, @PostAuthorize, @PreFilter, and @PostFilter by default. The older @EnableGlobalMethodSecurity is deprecated, and you should not use it.
Authority checks with SCOPE_ and ROLE_ prefixes
The expression functions compare strings against the authorities your converter produced.
| Expression | Matches authority |
|---|---|
| `hasAuthority('SCOPE_orders.read')` | exactly `SCOPE_orders.read` |
| `hasAnyAuthority('SCOPE_orders.read', 'SCOPE_orders.admin')` | either one |
| `hasRole('ADMIN')` | `ROLE_ADMIN` (the `ROLE_` prefix is added for you) |
| `isAuthenticated()` | any non-anonymous caller |
With the default converter, scopes become SCOPE_ authorities, so hasRole('admin') never matches a scope. If you configured the roles claim with the ROLE_ prefix, as in the earlier chapter, use hasRole. Mixing the two is a common source of unexplained 403 responses.
Using the token inside expressions
For a JWT login, the Authentication is a JwtAuthenticationToken and its principal is the Jwt. SpEL can reach both:
authentication.nameis thesubclaim by default.principal.claims['tenant']reads a custom claim.#idrefers to a method parameter namedid.
The #name syntax needs parameter names in the bytecode. Spring Boot's Maven and Gradle plugins compile with -parameters. Check this setting if you build another way.
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
record Order(long id, String ownerSub, String tenant, String item) {}
@Service
public class OrderService {
private final Map<Long, Order> orders = Map.of(
1L, new Order(1, "alice", "acme", "keyboard"),
2L, new Order(2, "bob", "acme", "monitor"));
@PreAuthorize("hasAuthority('SCOPE_orders.read')")
@PostAuthorize("returnObject.ownerSub == authentication.name "
+ "or hasAuthority('SCOPE_orders.admin')")
public Order find(long id) {
return Optional.ofNullable(orders.get(id))
.orElseThrow(() -> new NoSuchElementException("order " + id));
}
@PreAuthorize("hasAuthority('SCOPE_orders.read') "
+ "and principal.claims['tenant'] == #tenant")
public List<Order> listForTenant(String tenant) {
return orders.values().stream()
.filter(o -> o.tenant().equals(tenant))
.toList();
}
}find combines two annotations. @PreAuthorize runs before the body and checks the scope. @PostAuthorize runs after the body and can inspect returnObject, so it enforces ownership. listForTenant compares a token claim with an argument, so a caller cannot ask for another tenant's data by changing a parameter.
Choosing between @PreAuthorize and @PostAuthorize
| Annotation | Runs | Use when |
|---|---|---|
| `@PreAuthorize` | before the method | the decision needs only the caller and the arguments |
| `@PostAuthorize` | after the method | the decision needs the returned object |
The method body has already executed when @PostAuthorize fails. Do not use it on methods with side effects such as writes or emails. The side effect is not rolled back unless a transaction aborts on the exception.
Moving complex rules into a bean
Long expressions are hard to read and cannot be unit tested alone. Reference a Spring bean with @beanName and put the logic in Java:
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;
@Component("orderAccess")
public class OrderAccess {
public boolean canCancel(Authentication authentication, Order order) {
if (!(authentication instanceof JwtAuthenticationToken token)) {
return false;
}
Jwt jwt = token.getToken();
boolean sameTenant = order.tenant().equals(jwt.getClaimAsString("tenant"));
boolean owner = order.ownerSub().equals(jwt.getSubject());
return sameTenant && owner;
}
}@PreAuthorize("@orderAccess.canCancel(authentication, #order)")
public void cancel(Order order) {
// cancel the order
}The method returns false for any unexpected authentication type. The check fails closed, which is the right default for authorization code.
Failure modes and edge cases
- Self-invocation skips the check. Method security works through a proxy. If
findcallsthis.cancel(...), the call never crosses the proxy, socancel's annotation is ignored. Move the call to another bean or call through an injected reference. - Private and final methods are not protected. Annotate public methods on non-final classes.
- Exceptions can be swallowed.
AccessDeniedExceptionmust reach the filter chain so Spring Security answers with 403. A@ControllerAdvicewith a broad@ExceptionHandler(Exception.class)turns it into a 500 or 200. RethrowAccessDeniedException, or give it its own handler. - Null claims.
principal.claims['tenant']isnullwhen the claim is missing, so the comparison is false. AnullreturnObjectin@PostAuthorizethrows an evaluation error on property access, so checkreturnObject == null or ...or throw from the method as shown above. - Expression typos fail at call time. A wrong property name surfaces as an error when the method is first called, not at startup. Test every annotated method.
Testing method security
Test the service directly with @WithMockUser. The test below supplies a JwtDecoder that rejects every token, so the context starts without contacting an authorization server. Method security still applies because the service is a proxied bean.
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.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.jwt.BadJwtException;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.test.context.support.WithMockUser;
@SpringBootTest
@Import(OrderServiceTest.TestJwt.class)
class OrderServiceTest {
@TestConfiguration
static class TestJwt {
@Bean
JwtDecoder jwtDecoder() {
return token -> { throw new BadJwtException("not used in this test"); };
}
}
@Autowired
OrderService service;
@Test
@WithMockUser(username = "alice", authorities = "SCOPE_orders.read")
void ownerCanReadOwnOrder() {
assertThat(service.find(1).item()).isEqualTo("keyboard");
}
@Test
@WithMockUser(username = "alice", authorities = "SCOPE_orders.read")
void ownerCannotReadSomeoneElsesOrder() {
assertThatThrownBy(() -> service.find(2))
.isInstanceOf(AccessDeniedException.class);
}
@Test
@WithMockUser(username = "alice")
void missingScopeIsDenied() {
assertThatThrownBy(() -> service.find(1))
.isInstanceOf(AccessDeniedException.class);
}
}@WithMockUser creates a username and password authentication, not a JwtAuthenticationToken. Expressions that read principal.claims[...] fail with it, because the principal is not a Jwt. To test those, use jwt() through MockMvc as shown in the testing chapter, or build a JwtAuthenticationToken yourself and place it in the SecurityContext.
Exercise
A service method is annotated @PreAuthorize("hasRole('admin')"). Tokens from your authorization server carry the claim "scope": "admin", and you use the default JwtAuthenticationConverter. Every call returns 403. What is wrong, and what are two ways to fix it?
Show answer
The default converter turns the admin scope into the authority SCOPE_admin. hasRole('admin') looks for ROLE_admin, so it never matches. Fix it by changing the expression to hasAuthority('SCOPE_admin'), or by configuring a JwtGrantedAuthoritiesConverter that reads the claim you want and sets the authority prefix to ROLE_, then matching the exact case your tokens use.
Exercise
A method refund(long orderId) is annotated only with @PostAuthorize("returnObject.ownerSub == authentication.name") and it charges a card back before returning the order. Why is this unsafe, and how do you fix it?
Show answer
@PostAuthorize runs after the body, so the refund is already done when the check denies the caller. Add a @PreAuthorize that makes the decision before the body, for example by loading the order's owner through a bean (@orderAccess.canRefund(authentication, #orderId)), or enforce the ownership check inside the method before any side effect.