00:00

Spring Security Testing

Last updated:

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 @EnableMethodSecurity or 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 memberCannotReadAnotherMembersHolds explains the rule better than a comment.

3. The Main Testing Tools

ToolUse 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
@WithAnonymousUserRun 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

How MockMvc security tests runThe test method sets up a user with @WithMockUser or a request post-processor. MockMvc sends the simulated request through the real Spring Security filter chain and the controller, and the test asserts on status, headers and body. Test method @WithMockUser or .with(httpBasic(...)) MockMvc no server, no network Real filter chain CSRF, authentication, authorization Assertions status, headers, JSON body
Figure 1: tests run the real filter chain in memory; only the user setup is simulated.

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:

pom.xml (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());
    }
}

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());
    }
}

6. Step-by-Step Code Explanation

  1. @SpringBootTest + @AutoConfigureMockMvc start the full application context and give a MockMvc that routes requests through the real security filter chain.
  2. Negative tests first. The anonymous test expects 401 and the WWW-Authenticate header; the cross-member test expects 403 from @PreAuthorize.
  3. @WithMockUser skips the password check and sets the user directly, which keeps authorization tests fast and independent of real accounts.
  4. 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.
  5. httpBasic(...) exercises the real authentication with the real UserDetailsService and PasswordEncoder, for both a correct and a wrong password.
  6. HoldServiceTest calls the service bean directly. With @WithMockUser set, a denied call throws AuthorizationDeniedException, which proves the method rule independently of any URL rule.

7. Expected Output

Running the two test classes with Maven produced this summary:

Terminal
$ 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

AdvantagesLimitations
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 LoginBrowser behaviour (CORS enforcement, cookies across sites) still needs end-to-end tests
Method security testable without HTTPTests 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 @WebMvcTest without your security configuration. Slice tests only include web components; import your SecurityConfig explicitly or use @SpringBootTest.
  • Role prefixes in @WithMockUser. roles = "MEMBER" creates ROLE_MEMBER; use authorities = "claim:approve" for permissions.
  • Name tests after rules, such as librarianCanReadAnyMembersHolds, so a failing test explains which rule broke.

11. Summary

  • spring-security-test provides annotations such as @WithMockUser and MockMvc post-processors such as httpBasic() and csrf().
  • @SpringBootTest with @AutoConfigureMockMvc runs 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