liveBook · Manning

Authorization constraint

As explained in Spring Security in Action, Second Edition

An authorization configuration is a set of rules that determines which authenticated or unauthenticated requests may access application functionality.

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

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains path and method matching and gives MockMvc procedures, but stops short of implementing authentication providers.
Examples
Uses /hello tests with no user, @WithMockUser, username mary, and the user("mary") request post-processor.
What it assumes
Separates authentication from authorization through the security context and treats mock users as authorization-only test fixtures.
What you can do after
Evaluate authorization behavior with isolated MockMvc tests using controlled users, roles, authorities, and request contexts.
How it connects
Connects request matchers with authentication, roles, authorities, security context, MockMvc, and method security.

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.