Method security with @PreAuthorize
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Customers must never ship orders, even when a new controller, a scheduled job or another service calls the method that does it. URL rules alone cannot promise that.
@EnableMethodSecurity and @PreAuthorize
@PreAuthorize puts an access rule on one method. Spring checks the rule before the method runs and throws AuthorizationDeniedException (a kind of AccessDeniedException) if it fails.
URL rules see only the HTTP method and the path. A service method can be called from two controllers, a job or another service, so the rule belongs on the method too.
@Configuration@EnableMethodSecurity // turns on @PreAuthorize and @PostAuthorize for every beanpublic class SecurityConfig { ...}Example 1 · src/main/java/com/shoplite/lab/method/MethodSecurityLab.java
Runs in: the roles-lab Maven project (spring-boot-starter-security and oauth2-resource-server, Boot 4.1.1)
package com.shoplite.lab.method;
import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.function.Supplier;
import org.springframework.boot.Banner;import org.springframework.boot.SpringApplication;import org.springframework.boot.WebApplicationType;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.security.access.AccessDeniedException;import org.springframework.security.access.prepost.PostAuthorize;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;import org.springframework.security.core.Authentication;import org.springframework.security.core.authority.AuthorityUtils;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.stereotype.Component;import org.springframework.stereotype.Service;
record LabOrder(int id, int customerId, String status) {}
/** The signed-in user. A getter, so SpEL can read authentication.principal.customerId. */class Shopper { private final String name; private final Integer customerId;
Shopper(String name, Integer customerId) { this.name = name; this.customerId = customerId; }
public String getName() { return name; } public Integer getCustomerId() { return customerId; }}
/** A rule too big for one line of SpEL lives in a bean; @PreAuthorize calls it as @orderAccess. */@Component("orderAccess")class OrderAccess {
public boolean canRead(Authentication authentication, int orderId) { boolean admin = authentication.getAuthorities().stream() .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")); LabOrder order = LabOrderService.ORDERS.get(orderId); Shopper shopper = (Shopper) authentication.getPrincipal(); return admin || (order != null && order.customerId() == shopper.getCustomerId()); }}
@Serviceclass LabOrderService {
static final Map<Integer, LabOrder> ORDERS = Map.of( 1, new LabOrder(1, 1, "DELIVERED"), 14, new LabOrder(14, 2, "SHIPPED"), 15, new LabOrder(15, 6, "PLACED"));
@PreAuthorize("hasRole('ADMIN')") public String ship(int orderId) { return "order " + orderId + " shipped"; }
/** #customerId is the method parameter; authentication is the caller. */ @PreAuthorize("hasRole('ADMIN') or #customerId == authentication.principal.customerId") public List<LabOrder> ordersOf(int customerId) { return ORDERS.values().stream() .filter(order -> order.customerId() == customerId) .sorted(Comparator.comparingInt(LabOrder::id)) .toList(); }
@PreAuthorize("@orderAccess.canRead(authentication, #orderId)") public LabOrder read(int orderId) { return ORDERS.get(orderId); }
/** The method runs first; the rule then checks what it returned. */ @PostAuthorize("hasRole('ADMIN') or returnObject.customerId() == authentication.principal.customerId") public LabOrder find(int orderId) { System.out.println(" (find ran and loaded order " + orderId + ")"); return ORDERS.get(orderId); }
/** Not guarded itself, and it calls ship() on "this": the proxy is skipped. */ public List<String> shipAllPlaced() { return ORDERS.values().stream() .filter(order -> order.status().equals("PLACED")) .map(order -> ship(order.id())) .toList(); }}
@SpringBootApplication@EnableMethodSecuritypublic class MethodSecurityLab {
public static void main(String[] args) { SpringApplication app = new SpringApplication(MethodSecurityLab.class); app.setWebApplicationType(WebApplicationType.NONE); app.setBannerMode(Banner.Mode.OFF); try (ConfigurableApplicationContext context = app.run(args)) { LabOrderService orders = context.getBean(LabOrderService.class); Authentication asha = user(new Shopper("asha", 1), "ROLE_CUSTOMER"); Authentication admin = user(new Shopper("admin", null), "ROLE_ADMIN");
call("asha ship(15) ", asha, () -> orders.ship(15)); call("admin ship(15) ", admin, () -> orders.ship(15)); call("asha ordersOf(1) ", asha, () -> orders.ordersOf(1)); call("asha ordersOf(2) ", asha, () -> orders.ordersOf(2)); call("admin ordersOf(2) ", admin, () -> orders.ordersOf(2)); call("asha read(1) ", asha, () -> orders.read(1)); call("asha read(14) ", asha, () -> orders.read(14)); call("asha find(14) ", asha, () -> orders.find(14)); call("asha shipAllPlaced() ", asha, orders::shipAllPlaced); } }
private static Authentication user(Shopper shopper, String role) { return UsernamePasswordAuthenticationToken.authenticated(shopper, null, AuthorityUtils.createAuthorityList(role)); }
private static void call(String label, Authentication who, Supplier<Object> action) { SecurityContextHolder.getContext().setAuthentication(who); try { System.out.println(label + "-> " + action.get()); } catch (AccessDeniedException e) { System.out.println(label + "-> " + e.getClass().getSimpleName() + ": " + e.getMessage()); } finally { SecurityContextHolder.clearContext(); } }}asha ship(15) -> AuthorizationDeniedException: Access Denied
admin ship(15) -> order 15 shipped
asha ordersOf(1) -> [LabOrder[id=1, customerId=1, status=DELIVERED]]
asha ordersOf(2) -> AuthorizationDeniedException: Access Denied
admin ordersOf(2) -> [LabOrder[id=14, customerId=2, status=SHIPPED]]
asha read(1) -> LabOrder[id=1, customerId=1, status=DELIVERED]
asha read(14) -> AuthorizationDeniedException: Access Denied
(find ran and loaded order 14)
asha find(14) -> AuthorizationDeniedException: Access Denied
asha shipAllPlaced() -> [order 15 shipped]What this code does
ship(15)has@PreAuthorize("hasRole('ADMIN')"): Asha getsAuthorizationDeniedException: Access Denied, the admin gets the result. The check ran in the proxy, before the method.ordersOfcompares the parameter#customerIdwith the caller'scustomerId;readasks the@orderAccessbean.find(14)shows@PostAuthorize: the body ran, then the result was refused.shipAllPlaced()is the self-invocation trap: it callsship()onthis, so no check ran and Asha shipped an order.
@EnableMethodSecurity on a configuration class switches the rules on for the whole app. Spring then wraps each guarded bean in a proxy, a generated subclass that runs the check and then calls the real method. In the lab, Asha and the admin call guarded methods.
@EnableGlobalMethodSecurity(prePostEnabled = true). It has been deprecated since Spring Security 5.8; use @EnableMethodSecurity, which turns on @PreAuthorize and @PostAuthorize by default.SpEL in rules: authentication, #parameters and @beans
SpEL is the Spring Expression Language, a small language Spring evaluates at run time. The text inside @PreAuthorize is SpEL, so a rule can read authentication, a #parameter or call an @bean.
ShopLite lets everyone list active products and only admins see inactive ones. A URL rule cannot judge the query value well, but the service method receives it in its ProductFilter.
Example 2 · src/main/java/com/shoplite/product/ProductService.java (part)
Runs in: the shoplite-api Spring Boot project
package com.shoplite.product;
import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
// Part of the class: the methods that changed in this lesson. The bodies are unchanged.@Service@Transactional(readOnly = true)public class ProductService {
/** Inactive products are for admins only: a guest gets 401, a customer 403. */ @PreAuthorize("!#filter.includeInactive() or hasRole('ADMIN')") public PageResponse<ProductResponse> search(ProductFilter filter, String sort, int page, int size) { ... }
public ProductResponse get(Integer id) { ... } // no rule: anyone may read one product
@Transactional @PreAuthorize("hasRole('ADMIN')") public ProductResponse create(CreateProductRequest request) { ... }
@Transactional @PreAuthorize("hasRole('ADMIN')") public ProductResponse replace(Integer id, UpdateProductRequest request) { ... }
@Transactional @PreAuthorize("hasRole('ADMIN')") public ProductResponse patch(Integer id, PatchProductRequest request) { ... }
@Transactional @PreAuthorize("hasRole('ADMIN')") public void delete(Integer id) { ... }
// takeStock and returnStock have no rule: OrderService calls them when any customer orders}HTTP/1.1 401
WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Sign in to use this endpoint.","instance":"/api/v1/products"}
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/products"}
HTTP/1.1 200
Content-Type: application/json
{"content":[{"id":15,"sku":"ACC-USBC1","name":"USB-C Cable 1m","categoryId":4,"categoryName":"Accessories","price":199.00,"stock":0,"isActive":false}],"page":0,"size":20,"totalElements":1,"totalPages":1}What this code does
- Every catalogue change has
@PreAuthorize("hasRole('ADMIN')"), on top of the URL rule for/api/v1/products/**.takeStockstays open because ordering is a customer action. searchuses the parameter:!#filter.includeInactive()is true for normal lists, so anyone passes; withincludeInactive=trueonlyhasRole('ADMIN')can make the rule true.- Real answers: the guest gets 401 and Asha 403 (after the fix in Example 4), the admin sees the inactive USB-C cable.
Besides hasRole(...), a rule can read authentication (the current caller), #name (a method parameter by name) and @beanName (any Spring bean, to call one of its methods).
Keep expressions short. When a rule needs a database lookup or more than one line, move it into a bean method, such as @orderAccess.canRead(authentication, #orderId) in the lab, so it can be tested like normal Java.
Fix the error
Fix the SpEL rule
The rule fails when the method is called. Pick the line that fixes it.
Round 1 of 2
Only admins may delete a product.
Error
SpelEvaluationException: EL1008E: Property or field 'ADMIN' cannot be found on object of type 'MethodSecurityExpressionRoot'
#filter works because Spring Boot's Maven setup compiles with -parameters, which keeps parameter names. Without it, SpEL sees #filter as null and the rule fails in confusing ways.@PostAuthorize: checking the return value
@PostAuthorize runs the method first and then checks a rule that can use returnObject, the value the method returned. If the rule fails, the caller gets an AccessDeniedException instead of the value.
Only the loaded order says who owns it. @PostAuthorize lets the method load order 14 first and checks the owner afterwards.
@PostAuthorize("hasRole('ADMIN') or returnObject.customerId() == authentication.principal.customerId")public LabOrder find(int orderId) { System.out.println(" (find ran and loaded order " + orderId + ")"); return ORDERS.get(orderId);}In the lab, find(14) loads Ravi's order, then the rule sees customerId 2 and refuses Asha. The line (find ran and loaded order 14) in the lab output proves the body ran before the check.
The weakness is the order of events. The database work is already done, a method that changes data has already changed it, and the client sees 403, which tells Asha that order 14 exists. ShopLite therefore checks ownership in the query itself (next lesson) and uses neither @PostAuthorize nor 403 for other people's orders.
URL rules and method rules together, and two traps
Defence in depth means more than one independent check, so one mistake does not open the door. In ShopLite a URL rule is the first gate and a @PreAuthorize rule on the service is the second.
Method rules catch an admin URL that someone forgot to guard. One trap hides them: a catch-all exception handler can turn a plain denial into a 500.
Example 3 · The catch-all handler turns a denial into 500
Runs in: the shoplite-api Spring Boot project
// src/main/java/com/shoplite/common/GlobalExceptionHandler.java (part), before the fix@ExceptionHandler(Exception.class)ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) { log.error("Unexpected error on {} {}", request.getMethod(), request.getRequestURI(), ex); return problem(HttpStatus.INTERNAL_SERVER_ERROR, "internal-error", "Internal server error", "Something went wrong on our side. Please try again later.", request.getRequestURI());}# then, as Asha:curl -i "http://localhost:8080/api/v1/products?includeInactive=true" -H "Authorization: Bearer $ASHA"HTTP/1.1 500
Content-Type: application/problem+json
Connection: close
{"type":"https://shoplite.example/problems/internal-error","title":"Internal server error","status":500,"detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/products"}
Server log:
ERROR 29008 --- [shoplite-api] [io-8080-exec-3] c.s.common.GlobalExceptionHandler : Unexpected error on GET /api/v1/products
org.springframework.security.authorization.AuthorizationDeniedException: Access Denied
at org.springframework.security.authorization.method.ThrowingMethodAuthorizationDeniedHandler.handleDeniedInvocation(ThrowingMethodAuthorizationDeniedHandler.java:38) ~[spring-security-core-7.1.1.jar!/:7.1.1]
...What this code does
@PreAuthorizethrewAuthorizationDeniedExceptioninside the controller call, so Spring MVC looked for an@ExceptionHandlerfirst and found the catch-all forException.- The client got 500 "Something went wrong" for a plain permission problem, and the log filled with stack traces. Guests got 500 too, instead of 401.
- URL-rule denials were fine, because they happen in the filter chain, before any controller and before the advice.
Example 4 · Throwing security exceptions on
Runs in: the shoplite-api Spring Boot project
// src/main/java/com/shoplite/common/GlobalExceptionHandler.java (part), after the fix
/** * Access denied inside a controller or service (for example by @PreAuthorize) is not ours to answer. * Throw it on, so ExceptionTranslationFilter sends 401 to a guest and 403 to a signed-in user. * Without this, the catch-all below would turn every denial into a 500. */@ExceptionHandler({AccessDeniedException.class, AuthenticationException.class})void rethrowSecurityException(RuntimeException ex) { throw ex;}
@ExceptionHandler(Exception.class)ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) { ... } // unchangedHTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/products"}
HTTP/1.1 401
WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Sign in to use this endpoint.","instance":"/api/v1/products"}What this code does
- The more specific
@ExceptionHandlerwins, soAccessDeniedExceptionandAuthenticationExceptionnow reach this method instead of the catch-all. - Throwing the exception again sends it out of the controller call to
ExceptionTranslationFilter, which knows the caller: 403 for Asha, 401 withWWW-Authenticate: Bearer ...for the guest. BadCredentialsExceptionat login still has its own handler (401 "Email or password is wrong."), because a handler for the exact class is closer than this one.
The second trap is self-invocation: a call from inside the same class (this.ship(...)) does not go through the proxy, so its @PreAuthorize never runs. In the lab, shipAllPlaced() has no rule and calls ship() internally, so Asha shipped order 15. Put the rule on the public entry method too, or move the guarded method to another bean.
The first trap happens because @PreAuthorize throws inside the controller call, so the @RestControllerAdvice sees the exception before Spring Security does. The fix is a handler that throws security exceptions on, so ExceptionTranslationFilter answers 401 or 403 as usual.
Find the bug
Find the method-security bug
Each snippet leaves a hole. Tap the wrong line, then check the fix.
shipAllPlaced() calls the guarded ship() on the same bean.
Round 1 of 3Testing method security with a service-level test
A service-level test calls the service bean directly, with no HTTP and no database, and sets the caller with @WithMockUser or @WithAnonymousUser. It proves the rule on the method itself, whatever the URL rules say.
A tiny Spring context with method security and one service is enough. These three tests call ProductService as a customer, as a guest and as the admin.
Example 5 · src/test/java/com/shoplite/product/ProductServiceSecurityTest.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.product;
import static org.assertj.core.api.Assertions.assertThatThrownBy;import static org.mockito.Mockito.verifyNoInteractions;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;import org.springframework.security.authorization.AuthorizationDeniedException;import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;import org.springframework.security.test.context.support.WithAnonymousUser;import org.springframework.security.test.context.support.WithMockUser;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import com.shoplite.category.CategoryService;import com.shoplite.common.ResourceNotFoundException;import com.shoplite.common.ShopLiteProperties;
/** * The @PreAuthorize rules on ProductService, with no web layer at all: even if a URL rule is * forgotten, or another class calls the service, a customer cannot change the catalogue. */@SpringJUnitConfig(ProductServiceSecurityTest.MethodSecurityOnly.class)class ProductServiceSecurityTest {
@Configuration @EnableMethodSecurity @Import(ProductService.class) static class MethodSecurityOnly { }
@MockitoBean private ProductRepository repository; @MockitoBean private CategoryService categoryService; @MockitoBean private ShopLiteProperties properties;
@Autowired private ProductService service;
@Test @WithMockUser(roles = "CUSTOMER") void customerCannotDeleteAProduct() { assertThatThrownBy(() -> service.delete(6)).isInstanceOf(AuthorizationDeniedException.class); verifyNoInteractions(repository); // denied before the method body ran }
@Test @WithAnonymousUser void guestCannotSeeInactiveProducts() { ProductFilter inactiveToo = new ProductFilter(null, null, null, null, false, true); assertThatThrownBy(() -> service.search(inactiveToo, "id", 0, 20)) .isInstanceOf(AuthorizationDeniedException.class); }
@Test @WithMockUser(roles = "ADMIN") void adminPassesTheCheck() { // The empty mock repository finds no product 6: a 404 error proves the method body ran assertThatThrownBy(() -> service.delete(6)).isInstanceOf(ResourceNotFoundException.class); }}$ ./mvnw test -Dtest=ProductServiceSecurityTest ... [INFO] Running com.shoplite.product.ProductServiceSecurityTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.250 s -- in com.shoplite.product.ProductServiceSecurityTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
What this code does
MethodSecurityOnlybuilds a context with method security andProductServiceonly; the three dependencies are Mockito mocks, so no database starts.@WithMockUser(roles = "CUSTOMER")puts a fake signed-in user withROLE_CUSTOMERinto the security context for that one test.- Three tests run in about six seconds: a customer and a guest are refused, and the admin reaches the method body.
A denied call throws AuthorizationDeniedException, and verifyNoInteractions(repository) shows that the method body never ran.
Test the allowed case too. For the admin, the empty mock repository makes delete(6) throw ResourceNotFoundException. That error can only come from inside the method, so the security check let the admin through.
Next step
Check your understanding
12 quick questions