liveBook · Manning

@WithMockUser

As explained in Spring Security in Action, Second Edition

@WithMockUser is a Spring Security test annotation that establishes a SecurityContext containing a configured mock authenticated user.

@WithMockUser establishes a test SecurityContext containing a mock authenticated user, allowing security tests to skip the authentication process and exercise authorization behavior. section 18.1

Use it to test authenticated behavior in several Spring Security scenarios:

  • Annotate a MockMvc test method to call a protected endpoint as an authenticated user. section 18.1
  • Rely on default user attributes when the test only needs authentication, or configure username, roles, or authorities when authorization depends on them. section 18.1
  • Annotate method-security tests that directly invoke an injected bean instead of calling an HTTP endpoint. section 18.4
  • Use the same annotation with WebTestClient for reactive endpoint tests. section 18.8

Authenticated MockMvc request

@Test @WithMockUser(username = "mary") public void helloAuthenticated() throws Exception { mvc.perform(get("/hello")) .andExpect(content().string("Hello, mary!")) .andExpect(status().isOk()); } section 18.1

Method-security authorization cases

@Test @WithMockUser(authorities = "read") void rejectsWrongAuthority() { assertThrows(AccessDeniedException.class, () -> nameService.getName()); } @Test @WithMockUser(authorities = "write") void acceptsRequiredAuthority() { assertEquals("Fantastico", nameService.getName()); } section 18.4

Figure 18.3 We skip the shaded components in the Spring Security authentication flow when executing a test. The test directly uses a mock SecurityContext, which contains the mock user you define to call the tested functionality.

Trace how the test bypasses authentication and places the mock user directly into the SecurityContext used by the tested functionality. section 18.1

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains SecurityContext setup, configurable user attributes, endpoint tests, method tests, and reactive usage; contrasts request-level alternatives.
Examples
Uses /hello tests, configured username mary, authority checks, and reactive WebTestClient calls.
What it assumes
Assumes basic Spring testing and security configuration; demonstrates required test dependencies, MockMvc, WebTestClient, and direct bean injection.
What you can do after
Apply @WithMockUser to construct authenticated security-test scenarios and verify authorization outcomes.
How it connects
Connects SecurityContext, authentication, authorization rules, MockMvc, method security, WebTestClient, and RequestPostProcessor.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.