Sub topic 12
Testing secured endpoints with Spring Security test support
This chapter assumes you can write a @WebMvcTest controller test with MockMvc and mock beans, and that you know the basics of Spring Security filters and authorities. It adds the Spring Security test support that lets those tests run as an authenticated user.
Why secured endpoints need extra setup
With spring-boot-starter-security on the classpath, every request to a @WebMvcTest is checked by the security filter chain. An unauthenticated request gets 401 or a redirect to the login page. A state-changing request (POST, PUT, DELETE) without a CSRF token gets 403. A test written as in the previous chapters will therefore fail until you tell it who is calling.
The spring-security-test library supplies this. Add it as a test dependency. Spring Boot's version management supplies the version, but spring-boot-starter-test does not include this library.
dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}Two ways to supply a user
Spring Security test support offers annotations and MockMvc request post-processors. Both place an authenticated user into the security context for the request. Neither one checks a password or calls your UserDetailsService.
| Approach | Example | Use it when |
|---|---|---|
| Annotation | `@WithMockUser(roles = "ADMIN")` | The whole test, or class, runs as one user |
| Request post-processor | `.with(user("ada").roles("ADMIN"))` | Each request in a test needs a different user |
A worked example
Assume a controller with two endpoints. GET /greetings/{name} requires any authenticated user. DELETE /greetings/{name} requires the ADMIN role, enforced by this configuration:
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.DELETE, "/greetings/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}The test imports that configuration, because @WebMvcTest includes SecurityFilterChain beans only when you register them. Recent Spring Boot versions pick up @Configuration classes that define one, but an explicit @Import makes the dependency obvious.
@WebMvcTest(GreetingController.class)
@Import(SecurityConfig.class)
class GreetingSecurityTest {
@Autowired
MockMvc mockMvc;
@MockitoBean
GreetingService service;
@Test
void anonymousUserIsRejected() throws Exception {
mockMvc.perform(get("/greetings/Ada"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser
void authenticatedUserCanRead() throws Exception {
when(service.greetingFor("Ada")).thenReturn("Hello, Ada");
mockMvc.perform(get("/greetings/Ada"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Ada"));
}
@Test
@WithMockUser(roles = "USER")
void plainUserCannotDelete() throws Exception {
mockMvc.perform(delete("/greetings/Ada").with(csrf()))
.andExpect(status().isForbidden());
}
@Test
void adminCanDelete() throws Exception {
mockMvc.perform(delete("/greetings/Ada")
.with(user("root").roles("ADMIN"))
.with(csrf()))
.andExpect(status().isNoContent());
}
}The imports come from org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors (user, csrf) and org.springframework.security.test.context.support.WithMockUser.
Common mistakes
- Forgetting
csrf()on writes. A POST or DELETE without a token returns403even for an admin. The test then fails for a reason that has nothing to do with roles. Add.with(csrf())to every state-changing request. - Mixing up
rolesandauthorities.roles = "ADMIN"produces the authorityROLE_ADMIN. If your rule useshasAuthority("ADMIN"), useauthorities = "ADMIN"instead. - Testing only the allowed path. Each protected endpoint needs at least an anonymous test and a wrong-role test, or a rule that was removed will go unnoticed.
Exercise
A test sends post("/greetings") with @WithMockUser(roles = "ADMIN") and gets 403, even though the rule is hasRole("ADMIN"). What is the most likely cause, and how do you fix it?
Show answer
The request is missing a CSRF token, so the filter chain rejects it before the role check matters. Add .with(csrf()) to the request.
Exercise
A rule uses hasAuthority("REPORT_READ"). Which annotation makes a test pass that rule?
Show answer
@WithMockUser(authorities = "REPORT_READ"). The roles attribute would add the prefix ROLE_ and not match.