Authorization constraints apply different access rules to different requests. Use requestMatchers() to select requests by path and HTTP method; use anyRequest() for all requests or any remaining requests. section 8.0
Test authorization constraints separately from authentication:
- Create a mock security context and assign the roles or authorities needed for each authorization scenario. section 18.1
- Call the endpoint without a user to verify that unauthenticated access is rejected. section 18.1
- Use @WithMockUser or a user() RequestPostProcessor to verify permitted access and response content. section 18.1
Testing a protected endpoint
A Spring Boot MockMvc test calls /hello without a user and expects HTTP 401. A second test adds @WithMockUser(username = "mary") and expects HTTP 200 with the appropriate greeting. section 18.1
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.
Visualizes how a test bypasses the authentication flow and directly supplies a mock SecurityContext containing the user used to evaluate authorization. section 18.1
