Sub topic 13
Testing secured endpoints
This chapter assumes you can write a Spring Boot REST controller, use JUnit 5, and have configured a SecurityFilterChain as in the earlier chapters. It shows how to check each security rule with MockMvc and the spring-security-test library.
Why test security rules
A security rule is code, and it can break like any other code. A refactor can change a matcher order or drop a role, and the API may then expose data or lock out valid users. Tests that exercise each rule catch these changes before release.
You should test three outcomes for each protected path:
| Caller | Expected status | Meaning |
|---|---|---|
| No credentials | 401 | Not authenticated |
| Authenticated, wrong role or scope | 403 | Authenticated but not allowed |
| Authenticated, right role or scope | 200 | Allowed |
Add the test dependency
spring-security-test supplies @WithMockUser and the request post-processors such as jwt().
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>How the test reaches the rules
@WebMvcTest loads only the web layer. It does not pick up your own SecurityFilterChain unless you import it, so add @Import(SecurityConfig.class). Without it, Spring Boot applies a default chain and your rules are not tested.
Write the tests
The controller below is a minimal target for the tests.
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class OrderController {
@GetMapping("/api/orders")
List<String> orders() {
return List.of("order-1");
}
}The test class covers the three outcomes from the table.
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.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(OrderController.class)
@Import(SecurityConfig.class)
class OrderControllerSecurityTest {
@Autowired
MockMvc mvc;
@Test
void anonymousIsRejected() throws Exception {
mvc.perform(get("/api/orders"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(roles = "USER")
void userCanReadOrders() throws Exception {
mvc.perform(get("/api/orders"))
.andExpect(status().isOk());
}
@Test
void jwtWithoutScopeIsForbidden() throws Exception {
mvc.perform(get("/api/orders").with(jwt()))
.andExpect(status().isForbidden());
}
}@WithMockUser(roles = "USER") places an authenticated user in the SecurityContext without running real authentication. Spring adds the ROLE_ prefix for you. The jwt() post-processor does the same for a bearer token. It builds a Jwt and skips signature checks, so no authorization server is needed.
Testing the resource server rules
If your chain uses oauth2ResourceServer, a @WebMvcTest also needs a JwtDecoder bean, because the auto-configuration cannot reach an issuer in a test. Provide a mock bean of that type. Then grant the scope explicitly:
mvc.perform(get("/api/orders")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))))
.andExpect(status().isOk());The authority name must match the rule exactly, including the SCOPE_ prefix.
Common errors
- A mock user gets 403 on a POST. CSRF protection is still on, or the path rule is wrong. If your chain keeps CSRF, add
.with(csrf())to state-changing requests. - Every test returns 200. The security chain was not loaded. Check the
@Import. - Role tests fail.
hasRole("ADMIN")expects the authorityROLE_ADMIN.@WithMockUser(authorities = "ADMIN")does not match it.
Exercise
A test sends GET /api/admin/users with @WithMockUser(roles = "USER") and the rule is hasRole("ADMIN"). Which status should the test expect, and why?
Show answer
403 Forbidden. The mock user is authenticated, so the filter chain does not return 401, but the user lacks ROLE_ADMIN, so the authorization check denies the request.