Video in progress
How do you test endpoints protected by Spring Security, and where is @WithMockUser not enough?
@WithMockUser puts a ready-made user into the SecurityContext and is handy for checking role-based permissions. But it bypasses the authentication layer: JWT parsing, filters, token expiry. Those need to be checked separately with the .with(jwt()) post-processor or a real token.
📖 Answer
For a permissions matrix, @WithMockUser works well:
@WebMvcTest(AdminController.class)
@Import(SecurityConfig.class)
class AdminControllerSecurityTest {
@Autowired MockMvc mvc;
@MockitoBean ReportService reports;
@Test
void anonim_401() throws Exception {
mvc.perform(get("/admin/reports")).andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(roles = "USER")
void oddiy_foydalanuvchi_403() throws Exception {
mvc.perform(get("/admin/reports")).andExpect(status().isForbidden());
}
@Test
void admin_jwt_bilan_200() throws Exception {
mvc.perform(get("/admin/reports")
.with(jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))))
.andExpect(status().isOk());
}
}
@Import(SecurityConfig.class) matters: without it, @WebMvcTest may use Boot's default configuration instead of your SecurityFilterChain, and the test checks the wrong rules.
Subtle points:
- on POST/PUT/DELETE, if CSRF is enabled, you get a 403 without
.with(csrf())and think it's a permissions problem; - if
@PreAuthorizeis at the method level, you also need to check it in the service test: the controller test doesn't see it because the service is mocked; @WithMockUserandjwt()don't check the token signature, issuer or expiry. For the JWT configuration I build a token signed with a real key and write one or two tests at the@SpringBootTestlevel.
I usually write at least three cases for every endpoint: anonymous, a role without permission, and a role with permission. Security regressions get caught in exactly this simple table.
Sign up to mark studied questions and save your progress.