Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Testing and Hardening

Testing Secured Endpoints in Spring Security

Test Spring Security rules with MockMvc: @WithMockUser, jwt() and csrf() request post-processors, 401 and 403 checks, a test matrix and a runnable Java test harness.

Security rules are code, and code that nobody tests breaks quietly. A refactor moves a requestMatchers line below anyRequest(), and suddenly an admin page is public. Tests catch this in seconds. Spring Security ships a test module (spring-security-test) that makes them short: you pretend to be a user without going through a real login.

The Spring test classes cannot run on this site, so the framework code is read-only. The runnable part is a small plain Java test harness that models the same idea: an application function, a fake identity and assertions about status codes.

Setup

XML
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

A web-layer test loads only controllers and the security configuration:

Java
@WebMvcTest(OrderController.class)
@Import(SecurityConfig.class)
class OrderControllerSecurityTest {

    @Autowired MockMvc mvc;

    @Test
    void anonymousGets401() throws Exception {
        mvc.perform(get("/api/orders"))
           .andExpect(status().isUnauthorized());
    }

    @Test
    @WithMockUser(roles = "USER")
    void userCanListOrders() throws Exception {
        mvc.perform(get("/api/orders"))
           .andExpect(status().isOk());
    }

    @Test
    @WithMockUser(roles = "USER")
    void userCannotOpenAdmin() throws Exception {
        mvc.perform(get("/api/admin/users"))
           .andExpect(status().isForbidden());
    }
}

@WithMockUser puts a fake Authentication into the security context before the test: default name user, role ROLE_USER. You can set username, roles and authorities. Use @WithAnonymousUser for the opposite, and @WithUserDetails("alice") to load a real user from your UserDetailsService.

Request post-processors

For finer control, use static helpers from SecurityMockMvcRequestPostProcessors:

Java
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

// Form login app: a POST needs a CSRF token
mvc.perform(post("/orders").with(user("alice").roles("USER")).with(csrf()))
   .andExpect(status().isCreated());

// JWT resource server: skip signature checks, set the claims you need
mvc.perform(get("/api/orders")
        .with(jwt().jwt(j -> j.subject("u-42").claim("scope", "read"))))
   .andExpect(status().isOk());

// Authorities directly
mvc.perform(get("/api/orders").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_read"))))
   .andExpect(status().isOk());

// OIDC login
mvc.perform(get("/me").with(oidcLogin().idToken(t -> t.claim("email", "[email protected]"))))
   .andExpect(status().isOk());

Without .with(csrf()) a POST in a form-login application returns 403, which is exactly what you want to assert in a negative test:

Java
mvc.perform(post("/orders").with(user("alice")))    // no csrf()
   .andExpect(status().isForbidden());

What to test

Do not test that Spring Security works. Test that your configuration says what you mean.

Case Expected
Anonymous on a protected URL 401 (API) or redirect to login (web)
Anonymous on a public URL 200
Wrong role 403
Right role 200
POST without CSRF token (session app) 403
Expired or malformed JWT (integration test with a real decoder) 401
Another user's resource 403 or 404 (method security, see ownership checks)

Security test recipe

Anonymous Expect 401 or redirect
Normal user Allowed on own area
Wrong role Expect 403
Admin Allowed everywhere

Write these four for every protected path

1 / 2

A runnable harness (stand-in)

The program below is a miniature of the same technique. App.handle is the system under test, Identity plays the role of @WithMockUser, and check produces readable pass or fail lines. Nothing here uses Spring: the point is the structure of a security test matrix.

Java A tiny security test matrix (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line fails on purpose: the author "expected" an admin to skip CSRF, but the rules say otherwise. Failing tests like this are where security misunderstandings show up, so read each assertion as a sentence about your policy.

Testing method security and ownership

Method security (for example @PreAuthorize("#id == authentication.name")) is tested on the service bean with @WithMockUser:

Java
@SpringBootTest
class DocumentServiceTest {

    @Autowired DocumentService service;

    @Test
    @WithMockUser(username = "alice")
    void cannotReadOthersDocument() {
        assertThrows(AccessDeniedException.class, () -> service.read("bob", 7L));
    }
}

AccessDeniedException is what a denied method call throws; the web layer translates it into 403.

Integration tests with a real token

Slice tests with jwt() skip validation, so also keep at least one integration test that sends a real signed token to the real decoder: it proves your issuer, audience and signature settings. Tools such as MockWebServer or a test JWK set let you do this without a live identity provider.

Name tests after behaviour (anonymousGets401, userCannotOpenAdmin) so a failure message reads as a policy violation. Keep the security test class next to the configuration it protects.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @WithMockUser do?

    It sets up a SecurityContext with a user, so tests can skip the login flow.
  2. 2. A POST test in a session-based app returns 403 for a logged-in user. What is the most likely missing piece?

    CSRF protection rejects state-changing requests without a token. Add .with(csrf()).
  3. 3. Which helper simulates a bearer token in a resource-server test?

    jwt() installs a JwtAuthenticationToken with the claims you set, without verifying a signature.
  4. 4. What should the unauthorized-user test for an admin URL expect?

    A logged-in user without the role is authenticated but forbidden. 401 is for missing credentials.

Summary

  • Test your security rules with MockMvc, @WithMockUser and the post-processors user(), jwt(), oidcLogin() and csrf().
  • Write the four-case recipe (anonymous, user, wrong role, admin) for every protected path.
  • Test negative cases such as missing CSRF tokens and foreign resources.
  • Add at least one integration test with a real token to verify decoder settings.
  • Read each test as a sentence about your policy.

Next: Password storage and migration