Testing secured endpoints with mock users
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A wrong security rule is a data leak: a guest creates a category, or one customer reads another customer's order. How do you prove, and keep proving, that ShopLite refuses what it must refuse?
spring-security-test and @WithMockUser
@WithMockUser is a spring-security-test annotation that runs a test as a made-up signed-in user with the roles you give. It sets a user name and roles only, with no token and no claims.
Mark a test with the user it should run as. The same request then meets the real security rules as a customer or as a guest.
@Test@WithMockUser(roles = "CUSTOMER") // user "user" with ROLE_CUSTOMERvoid customerGets403WhenCreating() throws Exception { ... }
@Test@WithAnonymousUser // a guest, no sign-invoid guestGets401WhenCreating() throws Exception { ... }spring-security-test (in spring-boot-starter-security-test) adds these helpers. @WithAnonymousUser makes the caller a guest. The test needs the real SecurityConfig, so ShopLite's security tests use @SpringBootTest with @AutoConfigureMockMvc: the user from the annotation then reaches the filter chain, the URL rules and @PreAuthorize.
A role and a name are enough for role rules such as "only admins change categories".
401 for anonymous, 403 for the wrong role
401 Unauthorized means the server does not know who you are: no token, or a bad one. 403 Forbidden means it knows who you are, and you may not do this.
Test every protected rule from three sides: a guest, the wrong role and the right role. Example 1 tests the category rules; Example 2 checks a table of callers in plain Java.
Example 1 · src/test/java/com/shoplite/category/CategorySecurityIT.java
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
package com.shoplite.category;
import static org.hamcrest.Matchers.startsWith;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;import org.springframework.http.MediaType;import org.springframework.security.test.context.support.WithAnonymousUser;import org.springframework.security.test.context.support.WithMockUser;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.jdbc.Sql;import org.springframework.test.web.servlet.MockMvc;import org.springframework.transaction.annotation.Transactional;
/** The real SecurityConfig decides: guests read, customers are refused, admins write. */@SpringBootTest@AutoConfigureMockMvc@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS)@Transactional // the admin's new category is rolled backclass CategorySecurityIT {
private static final String WEARABLES = """ {"name": "Wearables", "parentId": 1} """;
@Autowired private MockMvc mockMvc;
@Test @WithAnonymousUser void guestsCanReadCategories() throws Exception { mockMvc.perform(get("/api/v1/categories/2")).andExpect(status().isOk()); }
@Test @WithAnonymousUser void guestGets401WhenCreating() throws Exception { mockMvc.perform(post("/api/v1/categories").contentType(MediaType.APPLICATION_JSON).content(WEARABLES)) .andExpect(status().isUnauthorized()) .andExpect(header().string("WWW-Authenticate", startsWith("Bearer"))) .andExpect(jsonPath("$.type").value("https://shoplite.example/problems/unauthorized")) .andExpect(jsonPath("$.detail").value("Sign in to use this endpoint.")); }
@Test @WithMockUser(roles = "CUSTOMER") void customerGets403WhenCreating() throws Exception { mockMvc.perform(post("/api/v1/categories").contentType(MediaType.APPLICATION_JSON).content(WEARABLES)) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.type").value("https://shoplite.example/problems/forbidden")) .andExpect(jsonPath("$.detail").value("You do not have permission to do this.")); }
@Test @WithMockUser(roles = "ADMIN") void adminCanCreate() throws Exception { mockMvc.perform(post("/api/v1/categories").contentType(MediaType.APPLICATION_JSON).content(WEARABLES)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.id").value(8)); }}[INFO] Running com.shoplite.category.CategorySecurityIT
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.731 s -- in com.shoplite.category.CategorySecurityIT
The two refusals, as .andDo(print()) shows them (other headers left out):
Status = 401
Headers = [WWW-Authenticate:"Bearer resource_metadata="http://localhost/.well-known/oauth-protected-resource"", Content-Type:"application/problem+json"]
Body = {"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Sign in to use this endpoint.","instance":"/api/v1/categories"}
Status = 403
Body = {"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/categories"}What this code does
- The real
SecurityConfigruns:GETon categories is public, every other method needsROLE_ADMIN. - The guest gets 401 with
WWW-Authenticate: Bearer ...; the customer gets 403. Both bodies come from ShopLite'sSecurityProblems, in the contract's field order. - The admin's 201 proves the rule lets the right role through;
@Transactionalrolls the new category back.
Example 2 · An access table, checked row by row
import java.util.List;import java.util.Map;import java.util.Set;
/** A caller: no roles means a guest. customerId is set for customers only. */record Caller(String name, Set<String> roles, Integer customerId) { boolean signedIn() { return !roles.isEmpty(); }}
/** A cut-down copy of ShopLite's rules: URL rules first (401/403), then the owner check (404). */class AccessRules { static final Map<Integer, Integer> ORDER_OWNER = Map.of(1, 1, 14, 2, 16, 7);
static int status(Caller caller, String method, String path) { boolean catalogue = path.startsWith("/api/v1/categories") || path.startsWith("/api/v1/products"); if (catalogue && method.equals("GET")) { return 200; // guests may browse } if (!caller.signedIn()) { return 401; } if (catalogue) { if (!caller.roles().contains("ADMIN")) { return 403; // catalogue changes: admins only } return method.equals("POST") ? 201 : 200; } if (method.equals("GET") && path.startsWith("/api/v1/orders/")) { int orderId = Integer.parseInt(path.substring("/api/v1/orders/".length())); Integer owner = ORDER_OWNER.get(orderId); if (caller.roles().contains("ADMIN")) { return owner == null ? 404 : 200; } // a customer's query only finds their own orders: someone else's looks missing return owner != null && owner.equals(caller.customerId()) ? 200 : 404; } return 403; }}
public class AccessRulesDemo { public static void main(String[] args) { Caller guest = new Caller("guest", Set.of(), null); Caller asha = new Caller("asha", Set.of("CUSTOMER"), 1); Caller admin = new Caller("admin", Set.of("ADMIN"), null);
record Row(Caller caller, String method, String path, int expected) { } List<Row> table = List.of( new Row(guest, "GET", "/api/v1/categories/2", 200), new Row(guest, "POST", "/api/v1/categories", 401), new Row(asha, "POST", "/api/v1/categories", 403), new Row(admin, "POST", "/api/v1/categories", 201), new Row(asha, "DELETE", "/api/v1/categories/7", 403), new Row(asha, "GET", "/api/v1/orders/1", 200), new Row(asha, "GET", "/api/v1/orders/14", 404), new Row(asha, "GET", "/api/v1/orders/99", 404), new Row(admin, "GET", "/api/v1/orders/14", 200), new Row(guest, "GET", "/api/v1/orders/14", 401));
int passed = 0; for (Row row : table) { int actual = AccessRules.status(row.caller(), row.method(), row.path()); boolean ok = actual == row.expected(); passed += ok ? 1 : 0; System.out.printf("%-5s %-6s %-22s -> %d %s%n", row.caller().name(), row.method(), row.path(), actual, ok ? "PASS" : "FAIL (expected " + row.expected() + ")"); } System.out.println(passed + " of " + table.size() + " rows pass"); }}guest GET /api/v1/categories/2 -> 200 PASS guest POST /api/v1/categories -> 401 PASS asha POST /api/v1/categories -> 403 PASS admin POST /api/v1/categories -> 201 PASS asha DELETE /api/v1/categories/7 -> 403 PASS asha GET /api/v1/orders/1 -> 200 PASS asha GET /api/v1/orders/14 -> 404 PASS asha GET /api/v1/orders/99 -> 404 PASS admin GET /api/v1/orders/14 -> 200 PASS guest GET /api/v1/orders/14 -> 401 PASS 10 of 10 rows pass
What this code does
- Each row is one caller, one request and the status it must get, like a row of
AccessMatrixIT's@CsvSource. - The rules are checked in ShopLite's order: public reads, then sign-in (401), then role (403), then the owner check (404).
- Asha's request for order 14 and for order 99 give the same 404: she cannot tell "not yours" from "missing".
ShopLite answers both refusals with a ProblemDetail (unauthorized, forbidden), and the 401 carries a WWW-Authenticate: Bearer ... header. A guest gets 401, a signed-in user with the wrong role gets 403, the right role gets the success status.
The "allowed" test matters as much as the refusals: a rule that refuses everyone would pass the other two. A table of caller, method, URL and expected status keeps many rules readable; ShopLite's AccessMatrixIT does this with @ParameterizedTest and @CsvSource.
Predict the output
Which status?
ShopLite allows guests to read categories. Pick the status for each request.
Round 1 of 3
Which status comes back?
jwt() request post-processor for JWT resource servers
jwt() is a MockMvc request post-processor from spring-security-test. It signs a request in as a JWT user with the claims and authorities you give, without creating or checking a real token.
Use jwt() when the code reads token claims, such as the customerId for /api/v1/me/.... Example 3 shows the call; Example 4 shows the trap.
Example 3 · src/test/java/com/shoplite/order/MyOrdersIT.java
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
package com.shoplite.order;
import static org.hamcrest.Matchers.everyItem;import static org.hamcrest.Matchers.is;import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.jdbc.Sql;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.request.RequestPostProcessor;
/** /api/v1/me/orders reads the customer id from the token, so the test needs a JWT, not just a role. */@SpringBootTest@AutoConfigureMockMvc@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS)class MyOrdersIT {
@Autowired private MockMvc mockMvc;
/** Asha: user 2, customer 1, with the claims ShopLite's real tokens carry. */ private static RequestPostProcessor asha() { return jwt() .jwt(token -> token.subject("2").claim("customerId", 1).claim("roles", List.of("CUSTOMER"))) .authorities(new SimpleGrantedAuthority("ROLE_CUSTOMER")); }
@Test void ashaSeesOnlyHerOwnOrdersNewestFirst() throws Exception { mockMvc.perform(get("/api/v1/me/orders").with(asha())) .andExpect(status().isOk()) .andExpect(jsonPath("$.totalElements").value(3)) .andExpect(jsonPath("$.content[*].customerId", everyItem(is(1)))) .andExpect(jsonPath("$.content[0].id").value(10)); }
@Test void claimsAloneDoNotGiveARole() throws Exception { // jwt() does not run ShopLite's roles converter: without .authorities(...) the caller has SCOPE_read only mockMvc.perform(get("/api/v1/me/orders") .with(jwt().jwt(token -> token.subject("2").claim("customerId", 1) .claim("roles", List.of("CUSTOMER"))))) .andExpect(status().isForbidden()); }}[INFO] Running com.shoplite.order.MyOrdersIT [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.402 s -- in com.shoplite.order.MyOrdersIT
What this code does
jwt().jwt(token -> ...)sets the claims the controller reads (subject,customerId);.authorities(...)sets the role the URL rule checks.- Asha (customer 1) has orders 1, 3 and 10; the newest, 10, comes first, and every item has
customerId1. - The second test proves the trap: the same claims without
.authorities(...)give 403, becausejwt()skipped the roles converter.
Example 4 · Claims are not authorities: what jwt() skips
import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;
/** * ShopLite's converter turns the token's "roles" claim into ROLE_ authorities. * A test helper that skips the converter must set the authorities itself. */public class TokenRolesDemo {
/** What SecurityConfig's JwtGrantedAuthoritiesConverter does: "roles" -> "ROLE_" + each role. */ static Set<String> convert(Map<String, Object> claims) { @SuppressWarnings("unchecked") List<String> roles = (List<String>) claims.getOrDefault("roles", List.of()); return roles.stream().map(role -> "ROLE_" + role).collect(Collectors.toSet()); }
static String hasRoleAdmin(Set<String> authorities) { return authorities.contains("ROLE_ADMIN") ? "allowed" : "403 Forbidden"; }
public static void main(String[] args) { Map<String, Object> claims = Map.of("sub", "1", "roles", List.of("ADMIN"));
// A real request: the token is decoded and the converter runs Set<String> real = convert(claims); System.out.println("real token authorities=" + real + " -> " + hasRoleAdmin(real));
// jwt() in a test with only claims: the converter does NOT run, the default authority is used Set<String> testDefault = Set.of("SCOPE_read"); System.out.println("jwt() claims only authorities=" + testDefault + " -> " + hasRoleAdmin(testDefault));
// jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN")): the test sets them itself Set<String> testExplicit = Set.of("ROLE_ADMIN"); System.out.println("jwt().authorities() authorities=" + testExplicit + " -> " + hasRoleAdmin(testExplicit)); }}real token authorities=[ROLE_ADMIN] -> allowed jwt() claims only authorities=[SCOPE_read] -> 403 Forbidden jwt().authorities() authorities=[ROLE_ADMIN] -> allowed
What this code does
- For a real request, ShopLite's converter maps
"roles": ["ADMIN"]toROLE_ADMIN. jwt()with claims only uses its default authoritySCOPE_read, sohasRole('ADMIN')refuses with 403.- Setting the authorities on
jwt()gives the test the same rights a real admin token gets.
The call looks like .with(jwt().jwt(token -> token.subject("2").claim("customerId", 1))). The test skips the signature and goes straight to an authenticated request, which keeps it fast and free of secrets; the real login and token checks are tested once in JwtAuthenticationIT.
The trap: jwt() does not run ShopLite's converter that turns the roles claim into ROLE_ authorities. Its default authority is SCOPE_read, so hasRole("CUSTOMER") refuses. Always add .authorities(new SimpleGrantedAuthority("ROLE_CUSTOMER")).
Fix the error
Fix the 403
The customer is refused although the token says CUSTOMER. Pick the fix.
Which replacement for line 3 makes the request pass?
Error
Status expected:<200> but was:<403>
Ownership: a customer cannot read another customer's order
A negative test tries something that must be refused, such as reading another customer's order, and expects the refusal. It proves the rule really blocks, not only that the normal path works.
Asha tries to read and cancel Ravi's order and must always get 404. Example 5 tests this on ShopLite; Example 6 shows the owner check in plain Java.
Example 5 · src/test/java/com/shoplite/order/OrderOwnershipIT.java (part)
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
// src/test/java/com/shoplite/order/OrderOwnershipIT.java (part; the full class is in your repository)@SpringBootTest@AutoConfigureMockMvc@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)class OrderOwnershipIT {
@Autowired private MockMvcTester mvc;
@Autowired private JdbcClient jdbc;
/** Asha (customer 1), signed in with the claims ShopLite's tokens carry. */ private static final RequestPostProcessor ASHA = jwt() .jwt(token -> token.subject("2").claim("customerId", 1) .claim("roles", List.of("CUSTOMER"))) .authorities(new SimpleGrantedAuthority("ROLE_CUSTOMER"));
@Test void ownerReadsOwnOrder() { assertThat(mvc.get().uri("/api/v1/orders/1").with(ASHA)).hasStatusOk(); }
@Test void otherCustomersOrderIs404() { assertThat(mvc.get().uri("/api/v1/orders/14").with(ASHA)) .hasStatus(HttpStatus.NOT_FOUND) .bodyJson().extractingPath("$.detail").isEqualTo("Order 14 was not found."); }
@Test void cannotCancelOtherCustomersOrder() { assertThat(mvc.post().uri("/api/v1/orders/16/cancel").with(ASHA)).hasStatus(HttpStatus.NOT_FOUND); String status = jdbc.sql("SELECT status FROM orders WHERE order_id = 16").query(String.class).single(); assertThat(status).isEqualTo("PLACED"); // nothing changed in the database }
@Test void customerCannotShip() { assertThat(mvc.post().uri("/api/v1/orders/15/ship").with(ASHA)).hasStatus(HttpStatus.FORBIDDEN); }
@Test void noTokenIs401() { assertThat(mvc.get().uri("/api/v1/orders/14")).hasStatus(HttpStatus.UNAUTHORIZED); }}[INFO] Running com.shoplite.order.OrderOwnershipIT [INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.137 s -- in com.shoplite.order.OrderOwnershipIT
What this code does
- Asha reads her own order 1 (200); Ravi's order 14 is 404 with the same text as a missing order.
- The cancel test checks the database with
JdbcClientafterwards: the refused request must change nothing. - The class also covers 403 (a customer cannot ship) and 401 (no token), so all three refusals are pinned down.
Example 6 · Owner check in the query: 404 for other people's orders
import java.util.List;import java.util.Optional;
record Order(int id, int customerId, String status) {}
class ResourceNotFoundException extends RuntimeException { ResourceNotFoundException(String resource, int id) { super(resource + " " + id + " was not found."); }}
/** The signed-in user, as ShopLite builds it from the token: admin, or a customer with an id. */record CurrentUser(int userId, Integer customerId, boolean admin) {}
class OrderStore { private final List<Order> rows = List.of(new Order(1, 1, "DELIVERED"), new Order(14, 2, "SHIPPED"), new Order(16, 7, "PLACED"));
Optional<Order> findById(int id) { return rows.stream().filter(o -> o.id() == id).findFirst(); }
/** The owner is part of the query, like "where o.id = :id and o.customer.id = :customerId". */ Optional<Order> findByIdAndCustomerId(int id, int customerId) { return rows.stream().filter(o -> o.id() == id && o.customerId() == customerId).findFirst(); }}
class OrderReader { private final OrderStore store;
OrderReader(OrderStore store) { this.store = store; }
Order get(int id, CurrentUser user) { Optional<Order> order = user.admin() ? store.findById(id) : store.findByIdAndCustomerId(id, user.customerId()); return order.orElseThrow(() -> new ResourceNotFoundException("Order", id)); }}
public class OwnerCheckDemo { static void read(String who, OrderReader reader, int id, CurrentUser user) { try { Order order = reader.get(id, user); System.out.println(who + " reads order " + id + " -> 200 " + order); } catch (ResourceNotFoundException e) { System.out.println(who + " reads order " + id + " -> 404 " + e.getMessage()); } }
public static void main(String[] args) { OrderReader reader = new OrderReader(new OrderStore()); CurrentUser asha = new CurrentUser(2, 1, false); CurrentUser admin = new CurrentUser(1, null, true);
read("asha ", reader, 1, asha); read("asha ", reader, 14, asha); // Ravi's order: looks exactly like a missing one read("asha ", reader, 99, asha); read("admin", reader, 14, admin); }}asha reads order 1 -> 200 Order[id=1, customerId=1, status=DELIVERED] asha reads order 14 -> 404 Order 14 was not found. asha reads order 99 -> 404 Order 99 was not found. admin reads order 14 -> 200 Order[id=14, customerId=2, status=SHIPPED]
What this code does
- For customers the lookup includes the customer id, like a
findByIdAndCustomerIdquery; admins use plainfindById. - Asha's request for order 14 finds no row and throws the same
ResourceNotFoundExceptionas order 99. - A test for this rule needs both sides: the owner (200), another customer (404), and an admin (200).
An ownership rule says a user may only touch their own data. ShopLite checks it in the query: a customer's order lookup includes their customer id, so Ravi's order 14 does not exist for Asha and she gets 404, the same answer as for a missing order. A 403 would tell her the order exists. Read someone else's order, its items, cancel it, and then check in the database that nothing changed.
Add the matching positive tests too: the owner reads their order (200) and an admin reads any order (200). Without them, a bug that hides every order would pass.
Order of execution
Order a negative test
Put the steps of the 'cannot cancel another customer's order' test in order.
Next step
Check your understanding
11 quick questions