liveBook · Manning

RequestPostProcessor

As explained in Spring Security in Action, Second Edition

A request postprocessor is a test component that modifies or prepares a simulated HTTP request before it is executed.

A RequestPostProcessor modifies a simulated HTTP request or its execution environment immediately before MockMvc sends it. In security tests, this lets each request define authentication, authorities, roles, or other security conditions without changing the application configuration. section 18.1

Use the supplied Spring Security implementations to prepare common test scenarios:

  • Call .with(user("mary")) to attach a mock user to a request. section 18.1
  • Call .with(csrf()) to add a CSRF token and verify that a mutating request succeeds; without it, the request returns 403 Forbidden. section 18.6
  • Call .with(httpBasic("john", "12345")) to test valid or invalid HTTP Basic credentials. section 18.5
  • Use jwt() or opaqueToken() to simulate resource-server authentication. section 18.5

Testing an authenticated endpoint

With Spring Boot and MockMvc configured, perform get("/hello").with(user("mary")), then expect the response body and status. Unlike @WithMockUser, the request is built first and the postprocessor adds the test security environment afterward. section 18.1

Figure 18.5 The difference between using annotations and the RequestPostProcessor to create the test security environment. When using annotations, the framework sets up the test security environment first. When using a RequestPostProcessor, the test request is created and then changed to define other constraints such as the test security environment. In the figure, the points where the framework applies the test security environment are shaded.

Compare annotation-based security setup with request-level preparation: annotations configure the test environment before the method runs, whereas a RequestPostProcessor changes the constructed request before dispatch. section 18.1

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains request-building order and demonstrates several implementations, but stops short of their internal implementation details.
Examples
Demonstrates user(), csrf(), httpBasic(), formLogin(), jwt(), and opaqueToken() against authenticated and protected endpoints.
What it assumes
Assumes Spring Boot test setup, MockMvc, and basic security configuration while showing how to create test users and credentials.
What you can do after
Apply it via MockMvc to build requests that exercise authentication, authorization, CSRF, and resource-server behavior.
How it connects
Connects MockMvc with SecurityContext, mock users, CSRF protection, HTTP Basic authentication, form login, JWT, and opaque tokens.

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.