0 day streak
java / intermediate
Snippet

Injecting Mock JWT Claims into WebMvc Slice Tests Using SecurityMockMvcRequestPostProcessors

In Spring Security with OAuth2 resource servers, controller methods often rely on claims embedded in a `JwtAuthenticationToken`. The `SecurityMockMvcRequestPostProcessors.jwt()` utility simulates authenticated HTTP requests in lightweight `@WebMvcTest` slice tests without needing a running authorization server or real cryptographic token generation.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@WebMvcTest(AuditReportController.class)
class AuditReportControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void shouldAllowAccessWhenAuditorRolePresentInJwt() throws Exception {
mockMvc.perform(get("/api/v1/audit/financials")
.with(jwt().jwt(builder -> builder
.subject("auditor-101")
.claim("roles", List.of("ROLE_AUDITOR"))
.claim("department", "Finance"))))
.andExpect(status().isOk())
.andExpect(header().string("Content-Type", "application/json"));
}
}
spring
Breakdown
1
@WebMvcTest(AuditReportController.class)
Bootstraps a focused MVC test slice containing only web layer beans, including Spring Security filters.
2
.with(jwt().jwt(builder -> builder
Injects a customized Mock SecurityContext populated with a mock JWT into the request execution.
3
.claim("roles", List.of("ROLE_AUDITOR"))
Configures specific JWT claim attributes to satisfy @PreAuthorize role-checking expressions on the controller.
4
.andExpect(status().isOk())
Asserts that authorization passed successfully and the endpoint returned HTTP status 200.