Sub topic 13
Testing secured endpoints with MockMvc
This chapter assumes you have the resource server from the earlier chapters: a SecurityFilterChain with oauth2ResourceServer().jwt(), scope-based authorities, and an /orders endpoint guarded by @PreAuthorize. You also need basic JUnit 5 and MockMvc knowledge, and spring-security-test on the test classpath.
Why not use real tokens in tests
A real token needs a running authorization server, a signing key, and a valid expiry. Tests that depend on all of that are slow and fragile. Spring Security Test offers the jwt() request post-processor instead. It places an already authenticated JwtAuthenticationToken in the security context and skips signature checks, so you test your authorization rules and not the decoder.
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>Setting up the test slice
@WebMvcTest loads only the web layer. Import your security configuration explicitly, because the slice does not scan it. The resource server configuration still needs a JwtDecoder bean. With issuer-uri set, the real decoder would try to reach the issuer at startup, so replace it with a mock.
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.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
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.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(OrderController.class)
@Import(SecurityConfig.class)
class OrderControllerSecurityTest {
@Autowired
MockMvc mockMvc;
@MockitoBean
JwtDecoder jwtDecoder;
@Test
void ordersRequiresToken() throws Exception {
mockMvc.perform(get("/orders"))
.andExpect(status().isUnauthorized())
.andExpect(header().exists("WWW-Authenticate"));
}
@Test
void ordersAllowedWithScope() throws Exception {
mockMvc.perform(get("/orders")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))))
.andExpect(status().isOk());
}
@Test
void ordersForbiddenWithoutScope() throws Exception {
mockMvc.perform(get("/orders").with(jwt()))
.andExpect(status().isForbidden());
}
}On Spring Boot versions before 3.4, use @MockBean from org.springframework.boot.test.mock.mockito instead of @MockitoBean.
What each test proves
| Request | Authentication | Result |
|---|---|---|
| No `Authorization` header | None | 401 with a `WWW-Authenticate: Bearer` header |
| `jwt()` with no authorities | Valid token, wrong permissions | 403 |
| `jwt()` with `SCOPE_orders.read` | Valid token, right permissions | 200 |
The 401 and 403 cases fail for different reasons. The first has no identity, so the bearer token filter's entry point answers. The second has an identity, but the method security check denies it.
Adjusting the simulated token
The jwt() post-processor accepts customizations:
jwt().jwt(j -> j.subject("alice").claim("aud", List.of("orders-api")))sets claims, useful for testing/me.jwt().authorities(...)replaces the authorities derived from claims.jwt().authorities(converter)runs your ownConverter<Jwt, Collection<GrantedAuthority>>.
If you set authorities explicitly, your converter is bypassed. To test the mapping logic from the earlier chapter, unit test the JwtAuthenticationConverter directly by passing it a hand-built Jwt.
Exercise
A test calls get("/admin/users").with(jwt()) and the filter chain requires SCOPE_admin for /admin/**. Which status do you expect, and why is it not 401?
Show answer
You expect 403. The jwt() post-processor supplies an authenticated principal, so authentication succeeds. The request fails authorization because the principal lacks SCOPE_admin. A 401 would only occur when no valid token is present at all.