Sub topic 13
Testing secured endpoints with MockMvc
This chapter assumes you can write a Spring Boot controller test with MockMvc, and that you have the resource server configuration from the earlier chapters: a SecurityFilterChain with oauth2ResourceServer().jwt(), @EnableMethodSecurity, and the OrderController shown below. You need spring-boot-starter-test and spring-security-test on the test classpath.
By the end you will be able to test the three outcomes that matter for a secured endpoint (401, 200, 403), and you will know which parts of the real token pipeline these tests do not exercise.
What you are testing, and what you are skipping
In production, a request passes through the bearer token filter, the JwtDecoder (signature, issuer, expiry, audience), and the JwtAuthenticationConverter. Only then do authorization rules run. A controller test does not need a real authorization server or real signed tokens. The jwt() request post-processor from spring-security-test places an already-authenticated JwtAuthenticationToken into the security context, so the decoder and the converter are skipped.
This split drives the structure of your tests. Request-level and method-level rules are tested through MockMvc with jwt(). The decoder and the converter are tested separately, as shown later in this chapter.
The code under test
This is the controller from the previous chapter.
@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");
}
}@AuthenticationPrincipal Jwt jwt resolves to the token inside the JwtAuthenticationToken, so the /me endpoint can be tested by controlling the claims that jwt() builds.
Setting up a slice test
@WebMvcTest loads only the web layer. Your SecurityConfig is not picked up automatically in every Spring Boot version, so import it explicitly. The filter chain calls oauth2ResourceServer(...jwt...), which needs a JwtDecoder bean to exist. Provide a mock so the test never contacts the issuer.
import static org.hamcrest.Matchers.startsWith;
import static org.mockito.Mockito.when;
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.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.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.BadJwtException;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
@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());
}
@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());
}
@Test
void meExposesClaims() throws Exception {
mockMvc.perform(get("/me")
.with(jwt().jwt(token -> token
.subject("alice")
.issuer("https://issuer.example.com/realms/demo"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.sub").value("alice"));
}
@Test
void rejectedTokenProducesChallenge() throws Exception {
when(jwtDecoder.decode("bad-token")).thenThrow(new BadJwtException("rejected"));
mockMvc.perform(get("/orders").header(HttpHeaders.AUTHORIZATION, "Bearer bad-token"))
.andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer")));
}
}@MockitoBean is available from Spring Framework 6.2 (Spring Boot 3.4). On older versions, use @MockBean from org.springframework.boot.test.mock.mockito instead.
Reading the three outcomes
The first three tests map directly to the authentication and authorization split.
- 401: no authentication is present. The bearer token filter finds no
Authorizationheader, so the request stays anonymous. TheanyRequest().authenticated()rule then fails and the entry point answers 401. - 200:
jwt().authorities(...)replaces the default authorities with exactly the ones you list, so the test states plainly which authority grants access. - 403: the caller is authenticated but lacks the required authority. The bare
jwt()call gives a token whose default authority isSCOPE_read. That authority is notSCOPE_orders.read, so@PreAuthorizedenies the request.
The fifth test shows the one place where a real header is sent. The mocked decoder throws BadJwtException, and the framework converts that to a 401 with a WWW-Authenticate: Bearer ... challenge. This covers your error handling without needing a signed token.
Customizing the simulated token
The jwt() builder has several overloads for different needs.
| Call | Effect |
|---|---|
| `jwt()` | Valid token with default claims and a `SCOPE_read` authority |
| `jwt().authorities(...)` | Sets the granted authorities directly |
| `jwt().jwt(builder -> builder.claim("scope", "orders.read"))` | Edits claims; authorities are derived from the claims by the default scope converter |
| `jwt().jwt(...).authorities(...)` | Both; the explicit authorities win |
Choose between the second and third rows by what you are verifying. If the test is about what an endpoint does with claims (like /me), edit the claims. If it is about who may reach the endpoint, set authorities.
Testing request rules that have no controller
The chain permits /public/** for everyone. If no controller maps that path, the request passes security and ends in a 404. That result confirms security let it through.
@Test
void publicPathsSkipAuthentication() throws Exception {
mockMvc.perform(get("/public/ping"))
.andExpect(status().isNotFound());
}A 401 here would mean the rule order is wrong. Remember that requestMatchers rules are evaluated in order, so a broad rule placed before /public/** would shadow it.
Testing what jwt() skips
Because jwt() bypasses the converter, a test using it cannot tell you that your roles claim maps to ROLE_ authorities. Test the converter as a plain unit test with a hand-built Jwt.
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
class AuthorityMappingTest {
@Test
void rolesClaimBecomesRoleAuthorities() {
JwtGrantedAuthoritiesConverter authorities = new JwtGrantedAuthoritiesConverter();
authorities.setAuthoritiesClaimName("roles");
authorities.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authorities);
Jwt jwt = Jwt.withTokenValue("t")
.header("alg", "none")
.claim("roles", List.of("ADMIN", "AUDITOR"))
.build();
assertThat(converter.convert(jwt).getAuthorities())
.extracting(GrantedAuthority::getAuthority)
.containsExactlyInAnyOrder("ROLE_ADMIN", "ROLE_AUDITOR");
}
}The same approach works for the audience validator. Build a Jwt with and without orders-api in aud, run it through the OAuth2TokenValidator, and assert on the OAuth2TokenValidatorResult. Signature checking is the other piece no mock tests: for that, use an integration test against a test authorization server or a locally generated key pair with NimbusJwtDecoder.withPublicKey(...).
Common errors
- Context fails to start with a missing
JwtDecoder: the slice test has noissuer-urior decoder bean. Add the@MockitoBean JwtDecoder. - Every request returns 401 or 403 unexpectedly for POST requests: CSRF protection is on by default in Spring Security. A stateless token API normally disables it in the chain, but if your chain does not, add
.with(csrf())to state-changing test requests. @PreAuthorizeseems ignored:SecurityConfigwas not imported, or@EnableMethodSecurityis missing from the loaded configuration.- A passing 403 test that should be 401: an anonymous request is rejected as 401, never 403. If you see 403, a token was present.
Exercise
A test calls mockMvc.perform(get("/orders").with(jwt().jwt(t -> t.claim("roles", List.of("ADMIN"))))) and your converter maps roles to ROLE_ authorities. The endpoint requires hasRole('ADMIN'). The test returns 403. Why, and how do you fix the test so it also verifies the mapping?
Show answer
The jwt() post-processor builds the authentication itself and does not run your JwtAuthenticationConverter, so the roles claim is never turned into ROLE_ADMIN. The token ends up with only the default scope-based authority, and hasRole('ADMIN') denies it. To test the endpoint rule, add .authorities(new SimpleGrantedAuthority("ROLE_ADMIN")). To test the mapping itself, write a separate unit test that passes a hand-built Jwt through the converter, or send a real header with a mocked JwtDecoder that returns that Jwt.