Sub topic 11
Fine-grained checks with @PreAuthorize
This chapter assumes you have a working JWT resource server, as built in the setup chapters. It also assumes you know how scopes become SCOPE_ authorities and how request rules in a SecurityFilterChain work. Here you add checks on individual methods.
Why method security
Request rules match URL patterns. They cannot see which method runs, its arguments, or the data it returns. Method security runs inside the application, after the request has been routed. It is a good fit when:
- Two endpoints share a URL prefix but need different scopes.
- The decision depends on an argument, such as "callers may read only their own orders".
- A service method is called from several controllers and must always be protected.
Method security does not replace request rules. Keep the broad rules in the filter chain and add method checks for the finer ones. The two layers are both enforced, so a request must pass both.
Enabling it
Put @EnableMethodSecurity on a configuration class. The filter chain from the earlier chapter already has it:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
// SecurityFilterChain bean as before
}Without this annotation, @PreAuthorize is silently ignored. That is the most common reason a method check "does nothing".
Checking authorities
@PreAuthorize takes a Spring Expression Language (SpEL) expression. Spring evaluates it before the method body runs. If it is false, the call is rejected. The controller below injects the validated token and protects one endpoint by scope:
@RestController
class OrderController {
@GetMapping("/me")
Map<String, Object> me(@AuthenticationPrincipal Jwt jwt) {
return Map.of("sub", jwt.getSubject(), "issuer", jwt.getIssuer().toString());
}
@PreAuthorize("hasAuthority('SCOPE_orders.read')")
@GetMapping("/orders")
List<String> orders() {
return List.of("order-1", "order-2");
}
}The expression uses the exact authority string, including the SCOPE_ prefix. If you changed the prefix with a JwtAuthenticationConverter, use that prefix instead. hasRole('admin') checks for ROLE_admin, so use hasRole only when your authorities carry the ROLE_ prefix.
How the check happens
Spring wraps the bean in a proxy. The proxy evaluates the expression and then calls the real method.
An authenticated caller who fails the expression gets 403. A request with no valid token never reaches the proxy, because the filter chain returns 401 first.
Expressions that use arguments
Expressions can reference method parameters and the token. This lets you compare the caller's identity with the data requested:
@PreAuthorize("hasAuthority('SCOPE_orders.read') and #customerId == authentication.name")
@GetMapping("/customers/{customerId}/orders")
List<String> ordersFor(@PathVariable String customerId) {
return List.of("order-1");
}For a JWT, authentication.name is the sub claim by default. #customerId refers to the parameter with that name. Parameter names are available when you compile with the -parameters flag, which Spring Boot's Maven and Gradle plugins enable.
Common errors
| Symptom | Likely cause |
|---|---|
| Method is reachable without the scope | `@EnableMethodSecurity` is missing |
| Always 403 for a valid token | Wrong prefix, such as `orders.read` instead of `SCOPE_orders.read` |
| Check ignored on an internal call | The method was called from the same class, which bypasses the proxy |
| Check ignored on a private method | Proxies only intercept public methods of Spring beans |
Exercise
A caller sends a valid JWT with only the scope orders.write. The /orders method requires hasAuthority('SCOPE_orders.read'), and @EnableMethodSecurity is present. What status code does the caller get, and which component produces it?
Show answer
403 Forbidden. The token is valid, so the filter chain authenticates the caller. The method security proxy then evaluates the expression, finds no matching authority, and denies access. A 401 would only occur if the token were missing or invalid.