Sub topic 13
Testing secured endpoints
This chapter assumes you have a working SecurityFilterChain, either the HTTP Basic one or the JWT resource server one from earlier chapters. You should also know basic JUnit 5 and MockMvc. The goal is to turn your security rules into automated tests, so that a change to a matcher or a role name fails a build instead of reaching production.
What to test and which tool to use
A security test needs a way to say who is calling. Spring Security's test module, spring-security-test, supplies several ways to do that. Add it with test scope. Spring Boot manages its version.
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>With this module on the classpath, Spring Boot's MockMvc support applies the security filter chain automatically. Your tests exercise the real filters and the real authorization rules, not a bypass.
The diagram shows how to choose a tool based on what you are testing.
The main options are summarized below.
| Tool | Where it applies | What it does |
|---|---|---|
| `@WithMockUser` | Test method or class | Puts a fake authenticated user in the `SecurityContext` |
| `@WithUserDetails` | Test method or class | Loads a real user from your `UserDetailsService` |
| `user("name")` | Request post-processor | Same as `@WithMockUser`, for one request |
| `httpBasic(u, p)` | Request post-processor | Sends a real Basic header, so the password is checked |
| `jwt()` | Request post-processor | Installs an authenticated JWT without a signature check |
| `csrf()` | Request post-processor | Adds a valid CSRF token to the request |
A minimal controller to test
The examples below use this controller. It sits in the same package as the tests.
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/orders")
class OrderController {
@GetMapping
List<String> list() {
return List.of("order-1", "order-2");
}
}Testing role-based rules with MockMvc
Use @WebMvcTest to load only the web layer. It does not pick up your SecurityFilterChain bean on its own, because that is a plain @Configuration class. Add it with @Import, or your tests will run against Spring Boot's default security instead of your rules.
This test class targets the HTTP Basic chain from the SecurityConfig class.
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.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(OrderController.class)
@Import(SecurityConfig.class)
class OrderControllerSecurityTest {
@Autowired
MockMvc mvc;
@Test
void anonymousIsRejected() throws Exception {
mvc.perform(get("/api/orders"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(roles = "USER")
void userCanReadOrders() throws Exception {
mvc.perform(get("/api/orders"))
.andExpect(status().isOk());
}
@Test
@WithMockUser(roles = "GUEST")
void wrongRoleIsForbidden() throws Exception {
mvc.perform(get("/api/orders"))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(roles = "USER")
void userCannotReachAdminArea() throws Exception {
mvc.perform(get("/api/admin/stats"))
.andExpect(status().isForbidden());
}
}Each test pins down one outcome of the rules:
- An anonymous request gets 401 because no one is authenticated.
- A user with the wrong role gets 403 because they are authenticated but not allowed.
- The admin test returns 403 even though no
/api/admin/statscontroller exists. Authorization runs in the filter chain before any controller is chosen. An admin calling the same path would get 404, which is itself a useful check that security let the request through.
@WithMockUser(roles = "USER") creates a user named user with the authority ROLE_USER. The roles attribute adds the ROLE_ prefix for you. Use authorities = "orders.read" when your rules use hasAuthority.
Real credentials and real users
@WithMockUser skips password checking. To test the Basic authentication path itself, send credentials with the httpBasic post-processor. This needs your UserDetailsService and PasswordEncoder in the test context, for example by importing UserConfig.
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
mvc.perform(get("/api/orders").with(httpBasic("alice", "change-me")))
.andExpect(status().isOk());
mvc.perform(get("/api/orders").with(httpBasic("alice", "wrong")))
.andExpect(status().isUnauthorized());@WithUserDetails("alice") is a middle path. It loads alice from the UserDetailsService bean, so her real roles apply, but it still skips the password check.
Testing JWT-protected endpoints
For a resource server you do not want to mint and sign tokens in every test. The jwt() post-processor installs an already-validated JwtAuthenticationToken. It skips decoding and signature verification, so it tests your authorization rules, not your token validation.
Two details matter:
oauth2ResourceServerneeds aJwtDecoderbean to start. In a web slice test, supply a mock.@MockitoBeanis available from Spring Boot 3.4. On older versions use@MockBean.- A bare
jwt()grants only the authoritySCOPE_read. YourSCOPE_orders.readrule therefore rejects it.
This class assumes the resource server chain from the JWT chapter is in a class named ResourceServerConfig. It is a separate configuration from SecurityConfig, and you load only one of them in a given test.
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.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
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.status;
@WebMvcTest(OrderController.class)
@Import(ResourceServerConfig.class)
class OrderControllerJwtTest {
@Autowired
MockMvc mvc;
@MockitoBean
JwtDecoder jwtDecoder;
@Test
void missingTokenIsUnauthorized() throws Exception {
mvc.perform(get("/api/orders"))
.andExpect(status().isUnauthorized());
}
@Test
void jwtWithoutRequiredScopeIsForbidden() throws Exception {
mvc.perform(get("/api/orders").with(jwt()))
.andExpect(status().isForbidden());
}
@Test
void jwtWithRequiredScopeIsAllowed() throws Exception {
mvc.perform(get("/api/orders")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))))
.andExpect(status().isOk());
}
}The last test sets the authority directly. You can also model the token itself with jwt().jwt(j -> j.claim("scope", "orders.read")), which exercises the same scope-to-authority conversion your converter performs in production.
Testing state-changing requests and CSRF
If you keep CSRF protection on, for example for a session-based app, a POST without a token returns 403. Add the token with the csrf() post-processor.
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
mvc.perform(post("/orders").with(csrf()).with(user("alice").roles("USER")))
.andExpect(status().isOk());For a stateless API with CSRF disabled, csrf() is unnecessary. A test that posts without a token and expects success also documents that you disabled CSRF on purpose.
Testing method security
@PreAuthorize is enforced by a proxy around the bean, so you must call the method through the Spring-managed bean, not with new. A small Spring context is enough. This example tests the OrderService and MethodSecurityConfig classes from the method security chapter.
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig({MethodSecurityConfig.class, OrderService.class})
class OrderServiceSecurityTest {
@Autowired
OrderService service;
@Test
@WithMockUser(username = "alice")
void ownerCanReadOwnOrders() {
assertDoesNotThrow(() -> service.findOrders("alice"));
}
@Test
@WithMockUser(username = "alice")
void otherUsersOrdersAreDenied() {
assertThrows(AccessDeniedException.class, () -> service.findOrders("bob"));
}
@Test
@WithMockUser(username = "root", roles = "ADMIN")
void adminCanReadAnyOrders() {
assertDoesNotThrow(() -> service.findOrders("bob"));
}
}At the service layer there is no HTTP status. A denied call throws AccessDeniedException. In a web request, the filter chain translates that exception into 403.
Common errors
- Every request returns 401 or 403 unexpectedly. The slice did not load your chain. Check for
@Import(SecurityConfig.class). Without it, Boot applies default security and every request needs a login. - A mutating request returns 403 for a user who should pass. CSRF is enabled in the chain under test. Add
csrf()or confirm that you meant to disable it. jwt()tests fail at startup with a missingJwtDecoder. Add the mock bean shown above.- A
@PreAuthorizetest never throws. Method security is not enabled in the test context, or you called the method on an object you created withnew. - Tests pass because you used
@WithMockUsereverywhere. It bypasses authentication. Keep at least one test per chain that goes through real authentication, such ashttpBasicor a mockedJwtDecoderwith a real bearer header.
Exercise
A @WebMvcTest for /api/admin/** with @WithMockUser(roles = "ADMIN") fails with 401 instead of 200. The test class has no @Import. What is the most likely cause, and what is the fix?
Show answer
The web slice did not load your SecurityFilterChain, so Spring Boot's default security applied. It does not know the mock user's role rule and, depending on what else is configured, rejects the request. Add @Import(SecurityConfig.class) (or the class holding your chain) to the test. After that, the hasRole("ADMIN") rule applies, and the mock user passes it. If the response is then 404, security succeeded and only the controller is missing.
Exercise
Write the three assertions that cover a GET /api/orders rule requiring the authority SCOPE_orders.read on a JWT resource server. Name the status each one expects.
Show answer
No token: mvc.perform(get("/api/orders")) expects status().isUnauthorized() (401). A token with the wrong scope: .with(jwt()) expects status().isForbidden() (403). A token with the right scope: .with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))) expects status().isOk() (200).