Spring Security Testing
Testing Spring Security means proving, with automated tests, that every protected endpoint and method lets the right people in and keeps everyone else out. Security rules are code like any other, and they break the same way: a refactoring moves an endpoint, a rule is reordered, or an annotation is lost. Without tests, nobody notices until a real user sees data they should not.
Spring Security ships a dedicated test module that makes these tests short and fast. This tutorial covers the main tools (@WithMockUser, the MockMvc request post-processors and method security tests), then tests a small library-holds API, including the negative cases that matter most, and runs the suite.
1. What Is Spring Security Testing?
The spring-security-test module adds two kinds of helpers. Annotations such as @WithMockUser place a fake authenticated user into the SecurityContext for one test method. Request post-processors for MockMvc, such as httpBasic(...), csrf(), user(...) and jwt(), adjust a single simulated request.
Combined with Spring Boot's @SpringBootTest and @AutoConfigureMockMvc, requests pass through the real security filter chain without starting a server, so tests verify exactly the configuration that runs in production.
2. Why Test Security?
- Rules regress silently. A missing
@EnableMethodSecurityor a reordered matcher produces no compiler error and no startup failure. - Negative cases are the point. Most tests check that something works; security tests must also check that it is refused: 401 for strangers, 403 for the wrong role or owner.
- They document intent. A test named
memberCannotReadAnotherMembersHoldsexplains the rule better than a comment.
3. The Main Testing Tools
| Tool | Use it to |
|---|---|
@WithMockUser(username = "nisha", roles = "MEMBER") | Run a test as a fake user, without a password check |
@WithUserDetails("nisha") | Run as a user loaded from your UserDetailsService |
@WithAnonymousUser | Run as an anonymous user explicitly |
.with(httpBasic("nisha", "secret")) | Send real Basic credentials through the real authentication |
.with(user("nisha").roles("MEMBER")) | Fake user for a single request |
.with(csrf()) | Add a valid CSRF token to a POST, PUT or DELETE |
.with(jwt().authorities(...)) | Simulate a validated JWT for resource servers |
.with(oidcLogin()) | Simulate an OAuth2 Login user |
Import the post-processors statically from SecurityMockMvcRequestPostProcessors. In Spring Boot 4, @AutoConfigureMockMvc lives in org.springframework.boot.webmvc.test.autoconfigure and comes with the spring-boot-starter-webmvc-test dependency.
4. How a Security Test Works
5. A Complete Example: Testing a Library Holds API
Library members place holds on books and see their own holds; librarians see everyone's. The application uses HTTP Basic, CSRF protection and method security. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2, JUnit 5 and these test dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-test</artifactId>
<scope>test</scope>
</dependency>
5.1 The Application Under Test
package com.javabytechie.holds;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().hasAnyRole("MEMBER", "LIBRARIAN"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo member only
return new InMemoryUserDetailsManager(
User.withUsername("nisha").password(encoder.encode("nisha-pass")).roles("MEMBER").build());
}
}
package com.javabytechie.holds;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class HoldService {
@PreAuthorize("#member == authentication.name or hasRole('LIBRARIAN')")
public List<String> holdsOf(String member) {
return List.of(member + ": Sapiens (ready for pickup)");
}
}
package com.javabytechie.holds;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HoldController {
private final HoldService holds;
public HoldController(HoldService holds) {
this.holds = holds;
}
@GetMapping("/api/holds")
public List<String> mine(Principal principal) {
return holds.holdsOf(principal.getName());
}
@GetMapping("/api/holds/{member}")
public List<String> ofMember(@PathVariable String member) {
return holds.holdsOf(member);
}
@PostMapping("/api/holds")
@ResponseStatus(HttpStatus.CREATED)
public Map<String, String> place(@RequestBody Map<String, String> request, Principal principal) {
return Map.of("member", principal.getName(), "isbn", request.get("isbn"));
}
}
package com.javabytechie.holds;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HoldsApplication {
public static void main(String[] args) {
SpringApplication.run(HoldsApplication.class, args);
}
}
5.2 The Tests
package com.javabytechie.holds;
import static org.hamcrest.Matchers.startsWith;
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.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest(classes = HoldsApplication.class)
@AutoConfigureMockMvc
class HoldControllerTest {
@Autowired
MockMvc mvc;
@Test
void anonymousUserIsChallenged() throws Exception {
mvc.perform(get("/api/holds"))
.andExpect(status().isUnauthorized())
.andExpect(header().exists("WWW-Authenticate"));
}
@Test
@WithMockUser(username = "nisha", roles = "MEMBER")
void memberSeesOwnHolds() throws Exception {
mvc.perform(get("/api/holds"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0]", startsWith("nisha:")));
}
@Test
@WithMockUser(username = "nisha", roles = "MEMBER")
void memberCannotReadAnotherMembersHolds() throws Exception {
mvc.perform(get("/api/holds/arjun")).andExpect(status().isForbidden());
}
@Test
@WithMockUser(username = "meera", roles = "LIBRARIAN")
void librarianCanReadAnyMembersHolds() throws Exception {
mvc.perform(get("/api/holds/arjun")).andExpect(status().isOk());
}
@Test
@WithMockUser(username = "nisha", roles = "MEMBER")
void postWithoutCsrfTokenIsRejected() throws Exception {
mvc.perform(post("/api/holds").contentType(MediaType.APPLICATION_JSON).content("{\"isbn\":\"9780062316097\"}"))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(username = "nisha", roles = "MEMBER")
void postWithCsrfTokenCreatesHold() throws Exception {
mvc.perform(post("/api/holds").with(csrf())
.contentType(MediaType.APPLICATION_JSON).content("{\"isbn\":\"9780062316097\"}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.member").value("nisha"));
}
@Test
void realCredentialsAreAccepted() throws Exception {
mvc.perform(get("/api/holds").with(httpBasic("nisha", "nisha-pass")))
.andExpect(status().isOk());
}
@Test
void wrongPasswordIsRejected() throws Exception {
mvc.perform(get("/api/holds").with(httpBasic("nisha", "wrong")))
.andExpect(status().isUnauthorized());
}
}
package com.javabytechie.holds;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
// Method security tested directly, without HTTP
@SpringBootTest(classes = HoldsApplication.class)
class HoldServiceTest {
@Autowired
HoldService holds;
@Test
@WithMockUser(username = "nisha")
void ownerMayReadOwnHolds() {
assertThat(holds.holdsOf("nisha")).hasSize(1);
}
@Test
@WithMockUser(username = "nisha")
void otherMembersAreDenied() {
assertThatThrownBy(() -> holds.holdsOf("arjun"))
.isInstanceOf(AuthorizationDeniedException.class);
}
}
6. Step-by-Step Code Explanation
@SpringBootTest+@AutoConfigureMockMvcstart the full application context and give aMockMvcthat routes requests through the real security filter chain.- Negative tests first. The anonymous test expects 401 and the
WWW-Authenticateheader; the cross-member test expects 403 from@PreAuthorize. @WithMockUserskips the password check and sets the user directly, which keeps authorization tests fast and independent of real accounts.- CSRF in tests. MockMvc requests do not carry a CSRF token unless you add
.with(csrf()). The pair of POST tests proves that protection is on and that legitimate requests pass. httpBasic(...)exercises the real authentication with the realUserDetailsServiceandPasswordEncoder, for both a correct and a wrong password.HoldServiceTestcalls the service bean directly. With@WithMockUserset, a denied call throwsAuthorizationDeniedException, which proves the method rule independently of any URL rule.
7. Expected Output
Running the two test classes with Maven produced this summary:
$ mvn test -Dtest='Hold*Test'
Running com.javabytechie.holds.HoldServiceTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 in com.javabytechie.holds.HoldServiceTest
Running com.javabytechie.holds.HoldControllerTest
Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 in com.javabytechie.holds.HoldControllerTest
Tests run: 10, Failures: 0, Errors: 0, Skipped: 0
BUILD SUCCESS
All ten tests pass: eight through MockMvc and two directly on the service. If someone later removes @EnableMethodSecurity, memberCannotReadAnotherMembersHolds and otherMembersAreDenied fail immediately; if CSRF is disabled, postWithoutCsrfTokenIsRejected fails.
8. What to Test for Every Rule
A useful habit is to write the same small set of tests for each protected endpoint or method. It takes minutes and catches almost every regression:
- Anonymous access: 401 (or a login redirect for browser chains).
- Wrong role or authority: 403.
- Right role, wrong owner: 403, for every rule that depends on data.
- Right user: success, with a check on the response body so you know the right data came back.
- State-changing requests: 403 without a CSRF token in browser chains, success with one.
9. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Real filter chain and rules, no server needed | @SpringBootTest loads the whole context; slower than unit tests |
| Fake users make authorization tests simple | @WithMockUser skips authentication, so test that separately |
| Post-processors cover Basic, CSRF, JWT and OAuth2 Login | Browser behaviour (CORS enforcement, cookies across sites) still needs end-to-end tests |
| Method security testable without HTTP | Tests must be kept in sync when roles or URLs change |
10. Common Mistakes and Best Practices
- Only testing the happy path. For each rule, test at least one user who must be refused.
- Forgetting
.with(csrf())and then disabling CSRF in production to make tests pass. Add the token in the test instead. - Using
@WebMvcTestwithout your security configuration. Slice tests only include web components; import yourSecurityConfigexplicitly or use@SpringBootTest. - Role prefixes in
@WithMockUser.roles = "MEMBER"createsROLE_MEMBER; useauthorities = "claim:approve"for permissions. - Name tests after rules, such as
librarianCanReadAnyMembersHolds, so a failing test explains which rule broke.
11. Summary
spring-security-testprovides annotations such as@WithMockUserand MockMvc post-processors such ashttpBasic()andcsrf().@SpringBootTestwith@AutoConfigureMockMvcruns requests through the real filter chain without a server.- Test negative cases: 401 for anonymous users and wrong passwords, 403 for wrong roles, owners and missing CSRF tokens.
- Test method security directly on the bean and expect
AuthorizationDeniedException. - In Spring Boot 4, MockMvc test support lives in
spring-boot-starter-webmvc-test.
12. References
Frequently Asked Questions (FAQ)
Q1. What does @WithMockUser do?
It puts a fake authenticated user with the given username, roles or authorities into the SecurityContext for one test method. No password check takes place.
Q2. Why does my MockMvc POST test return 403?
Because CSRF protection is active and MockMvc does not add a token automatically. Add .with(csrf()) from SecurityMockMvcRequestPostProcessors.
Q3. How do I test real username and password authentication?
Send the request with .with(httpBasic("user", "password")), or formLogin() from SecurityMockMvcRequestBuilders, so the real UserDetailsService and PasswordEncoder are used.
Q4. How do I test @PreAuthorize methods?
Inject the bean in a @SpringBootTest, annotate the test with @WithMockUser, call the method and assert that it returns or throws AuthorizationDeniedException.
Q5. How do I test a JWT-protected endpoint?
Use .with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))). The post-processor creates a validated JWT authentication without contacting an issuer.