Sub topic 12
Testing secured endpoints with Spring Security test support
This chapter assumes you can write a @WebMvcTest controller test with MockMvc and replace collaborators with @MockitoBean. You should also know the basics of Spring Security: a filter chain, authentication, roles, and CSRF protection. Without extra setup, a secured endpoint turns your controller tests into a wall of 401 and 403 responses. Spring Security's test support lets you decide who is calling, then check what the endpoint does.
Why secured endpoints break plain tests
When Spring Security is on the classpath, Spring Boot auto-configures a filter chain that requires authentication for every request. A @WebMvcTest loads that web-layer security configuration too. A request without credentials is rejected before it reaches your controller.
Two failures show up most often:
401 Unauthorized: the request has no authenticated user.403 Forbidden: the user is authenticated but lacks the role, or the request is aPOST,PUT, orDELETEwithout a CSRF token.
Both mean the security layer worked. Your test has to supply the missing identity or token.
Adding the test dependency
The security test support is a separate module. It is not part of spring-boot-starter-test.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}With spring-security-test on the classpath, Spring Boot's MockMvc auto-configuration applies Spring Security to MockMvc for you. The security filter chain runs during mockMvc.perform(...), so your tests exercise the real rules.
A secured controller to test
The examples use a small controller. Anyone authenticated can read a greeting. Only users with the ADMIN role can delete one.
@RestController
@RequestMapping("/greetings")
class GreetingController {
private final GreetingService service;
GreetingController(GreetingService service) {
this.service = service;
}
@GetMapping("/{name}")
String greeting(@PathVariable String name) {
return service.greetingFor(name);
}
@DeleteMapping("/{name}")
@PreAuthorize("hasRole('ADMIN')")
ResponseEntity<Void> delete(@PathVariable String name) {
service.delete(name);
return ResponseEntity.noContent().build();
}
}The security configuration requires authentication for everything and enables method security.
@Configuration
@EnableMethodSecurity
class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}Testing the anonymous case
Start with the rule that matters most: an unauthenticated caller must be rejected.
@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());
}
}@Import(SecurityConfig.class) is needed because @WebMvcTest scans controllers and web-layer components, but it does not pick up arbitrary @Configuration classes. Without the import, Boot's default security applies instead of your rules, and the test can pass for the wrong reason.
Simulating a user with @WithMockUser
@WithMockUser places an authenticated user in the security context before the test runs. No password check and no login request happen.
@Test
@WithMockUser
void authenticatedUserCanReadGreeting() throws Exception {
when(service.greetingFor("Ada")).thenReturn("Hello, Ada");
mockMvc.perform(get("/greetings/Ada"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Ada"));
}
@Test
@WithMockUser(username = "grace", roles = "USER")
void plainUserCannotDelete() throws Exception {
mockMvc.perform(delete("/greetings/Ada").with(csrf()))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(roles = "ADMIN")
void adminCanDelete() throws Exception {
mockMvc.perform(delete("/greetings/Ada").with(csrf()))
.andExpect(status().isNoContent());
verify(service).delete("Ada");
}The defaults are username user, password password, and role USER. Use the roles attribute without the ROLE_ prefix. Spring adds the prefix. If you need exact authority strings, use authorities instead, for example authorities = "ROLE_ADMIN". Do not set both attributes.
You can place @WithMockUser on the test class to apply it to every method. A method-level annotation overrides the class-level one.
CSRF tokens on state-changing requests
By default, Spring Security rejects POST, PUT, PATCH, and DELETE requests that lack a valid CSRF token. The tests above call .with(csrf()), a request post-processor that adds a valid token. Leave it out and an authorized admin gets 403, which looks like a role problem but is not.
If your API is stateless and disables CSRF in its configuration, you do not need csrf() in those tests. Match the test to the real configuration.
Request post-processors versus annotations
Annotations such as @WithMockUser set up the security context for the whole test. Post-processors from SecurityMockMvcRequestPostProcessors configure a single request. Use them when one test needs several identities.
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
@Test
void roleDecidesOutcome() throws Exception {
mockMvc.perform(delete("/greetings/Ada")
.with(user("grace").roles("USER"))
.with(csrf()))
.andExpect(status().isForbidden());
mockMvc.perform(delete("/greetings/Ada")
.with(user("root").roles("ADMIN"))
.with(csrf()))
.andExpect(status().isNoContent());
}The httpBasic("user", "password") post-processor sends a real Authorization header. It is useful when you want to test the authentication mechanism itself instead of bypassing it. That needs a user store the test can authenticate against, for example an in-memory UserDetailsService bean.
| Approach | Scope | Skips authentication? | Typical use |
|---|---|---|---|
| `@WithMockUser` | Whole test or class | Yes | Authorization rules by role |
| `.with(user(...))` | One request | Yes | Several identities in one test |
| `.with(httpBasic(...))` | One request | No | Login mechanism and credentials |
| `@WithUserDetails` | Whole test or class | No, loads a real user | Custom `UserDetails` types |
Choosing an identity when your code reads the principal
@WithMockUser creates a standard User principal. If your controller reads a custom principal type through @AuthenticationPrincipal, the mock user's class will not match, and you may get a ClassCastException or a null. Use @WithUserDetails("ada") so Spring loads the user through your UserDetailsService. The user must exist in that service when the test runs.
How the request flows
The diagram shows what MockMvc does with a secured request in a @WebMvcTest. It shows why a rejected request never touches your controller or your mocked service.
Testing method security
@PreAuthorize is enforced by a proxy around the bean, not by the filter chain. In a @WebMvcTest the controller is proxied, so the delete tests above exercise it. When you test a secured service directly, you need a Spring context that creates the proxy. A plain Mockito unit test never applies @PreAuthorize.
@SpringBootTest
class AdminServiceSecurityTest {
@Autowired
AdminService adminService;
@Test
@WithMockUser(roles = "USER")
void userIsDenied() {
assertThatThrownBy(() -> adminService.purgeAll())
.isInstanceOf(AccessDeniedException.class);
}
@Test
@WithMockUser(roles = "ADMIN")
void adminIsAllowed() {
assertThatCode(() -> adminService.purgeAll()).doesNotThrowAnyException();
}
}This is a full-context test, so use it sparingly. Keep the rule tests focused on the few methods that carry real authorization logic.
Full-stack tests with security
With @SpringBootTest(webEnvironment = RANDOM_PORT) and TestRestTemplate, requests travel over real HTTP. @WithMockUser does not work there, because the test thread and the server thread are different, so the security context is not shared. Send real credentials instead.
@Test
void adminCanDeleteOverHttp() {
ResponseEntity<Void> response = restTemplate
.withBasicAuth("admin", "secret")
.exchange("/greetings/Ada", HttpMethod.DELETE, null, Void.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
}Define the admin user in a @TestConfiguration with an in-memory UserDetailsService, so the test does not depend on production credentials.
Common errors
- Every test returns 401. The test sends no identity. Add
@WithMockUseror a post-processor. - Every write returns 403. The CSRF token is missing. Add
.with(csrf()). - Your rules seem ignored. The
@WebMvcTestdid not import yourSecurityConfig. Add@Import. @WithMockUserhas no effect inTestRestTemplatetests. The server runs on another thread. Use real credentials.@PreAuthorizeis not enforced in a Mockito test. There is no proxy. Use a Spring context.- Role checks fail with
ROLE_ROLE_ADMIN. You included the prefix inroles. Drop it, or useauthorities.
Exercise
A test sends DELETE /greetings/Ada with @WithMockUser(roles = "ADMIN") and expects 204, but gets 403. The admin role is configured correctly and the controller uses @PreAuthorize("hasRole('ADMIN')"). What is the most likely cause, and how do you fix it?
Show answer
The request is missing a CSRF token. Spring Security rejects DELETE requests without one, even for an authorized user. Add .with(csrf()) to the request. If the real application disables CSRF for a stateless API, the test configuration should disable it as well.
Exercise
You switch a TestRestTemplate test from basic-auth credentials to @WithMockUser(roles = "ADMIN") and the request now returns 401. Why, and what should you do instead?
Show answer
With a random port the application handles the request on a server thread, and the test annotation populates the security context only on the test thread. The server never sees the mock user. Send real credentials with restTemplate.withBasicAuth(...), and define the matching user in a @TestConfiguration that provides an in-memory UserDetailsService.