Skip to lesson

URL rules with requestMatchers

ShopLite has over 30 endpoints. Checking the role inside every controller method means 20 chances to forget one, and an endpoint added next year stays open until someone remembers.

requestMatchers: method and path patterns

requestMatchers(...) selects the requests a URL rule applies to, by HTTP method and path. The rule then ends with what is required, such as permitAll() or hasRole("ADMIN").

Here is ShopLite's whole SecurityConfig after this module, written from the access table in SECURITY.md. Read it top to bottom, the way Spring checks it.

Example 1 · src/main/java/com/shoplite/common/security/SecurityConfig.java

Runs in: the shoplite-api Spring Boot project

SecurityConfig.javaJava
package com.shoplite.common.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.ProviderManager;import org.springframework.security.authentication.dao.DaoAuthenticationProvider;import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.factory.PasswordEncoderFactories;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;import org.springframework.security.web.SecurityFilterChain;
/** * Every URL rule of ShopLite lives in this one class, in the order of the access table in SECURITY.md. * Rules are checked from top to bottom; the first rule that matches a request decides. * Owner checks ("own order, else 404") live in the services, because a URL cannot know who owns order 14. */@Configuration@EnableMethodSecuritypublic class SecurityConfig {
    private static final String[] API_DOCS = { "/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html" };
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http, ProblemAuthenticationEntryPoint unauthorized,                                            ProblemAccessDeniedHandler forbidden) throws Exception {        http            .authorizeHttpRequests(auth -> auth                .requestMatchers(HttpMethod.POST, "/api/v1/auth/**").permitAll()                .requestMatchers(HttpMethod.GET, "/api/v1/products/**", "/api/v1/categories/**").permitAll()                .requestMatchers(HttpMethod.GET, "/api").permitAll()                .requestMatchers("/actuator/health/**").permitAll()                .requestMatchers(API_DOCS).permitAll()                .requestMatchers("/error").permitAll()                // Catalogue changes (every other method on these paths): admins only                .requestMatchers("/api/v1/products/**", "/api/v1/categories/**").hasRole("ADMIN")                .requestMatchers("/api/v1/me/**").hasRole("CUSTOMER")                // One order: its owner or an admin (OrderService answers 404 for other customers)                .requestMatchers(HttpMethod.GET, "/api/v1/orders/*", "/api/v1/orders/*/items")                    .hasAnyRole("CUSTOMER", "ADMIN")                .requestMatchers(HttpMethod.POST, "/api/v1/orders/*/cancel").hasAnyRole("CUSTOMER", "ADMIN")                .requestMatchers("/api/v1/orders/**", "/api/v1/customers/**").hasRole("ADMIN")                // Anything not listed above, including endpoints added later and forgotten here                .anyRequest().denyAll())            .oauth2ResourceServer(oauth -> oauth                .jwt(jwt -> jwt.jwtAuthenticationConverter(rolesFromToken()))                .authenticationEntryPoint(unauthorized)                .accessDeniedHandler(forbidden))            .exceptionHandling(ex -> ex                .authenticationEntryPoint(unauthorized)                .accessDeniedHandler(forbidden))            .csrf(csrf -> csrf.disable())            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));        return http.build();    }
    /** The token's "roles" claim ["CUSTOMER"] becomes the authority ROLE_CUSTOMER. */    private static JwtAuthenticationConverter rolesFromToken() {        JwtGrantedAuthoritiesConverter authorities = new JwtGrantedAuthoritiesConverter();        authorities.setAuthoritiesClaimName("roles");        authorities.setAuthorityPrefix("ROLE_");        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();        converter.setJwtGrantedAuthoritiesConverter(authorities);        return converter;    }
    /** Checks e-mail and password at login: users from MySQL, BCrypt hashes. */    @Bean    AuthenticationManager authenticationManager(UserDetailsService users, PasswordEncoder passwordEncoder) {        DaoAuthenticationProvider provider = new DaoAuthenticationProvider(users);        provider.setPasswordEncoder(passwordEncoder);        return new ProviderManager(provider);    }
    @Bean    PasswordEncoder passwordEncoder() {        return PasswordEncoderFactories.createDelegatingPasswordEncoder();    }}
Sample output
... INFO ... com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 9.8 seconds (process running for 10.6)

What this code does

  • The rules follow the access table: guests and public paths first, then the catalogue writes, /me, single orders, the admin-only areas, and denyAll() last.
  • GET /api/v1/products/** is public, and the next rule (all other methods on the same paths) is admin-only. Swapping these two lines would close the catalogue.
  • @EnableMethodSecurity switches on @PreAuthorize, used in the next lesson.
  • CSRF is switched off and sessions are stateless because tokens travel in the Authorization header, never in a cookie. The error handlers come in the 401 vs 403 lesson.

Leave out the method and a rule covers every method. Paths use Spring's PathPattern language, so one rule on /api/v1/customers/** also covers customer endpoints added next year.

permitAll, authenticated, hasRole and hasAnyRole side by side

permitAll() lets everyone in, even with no token; denyAll() refuses everyone. Between them sit authenticated() (any signed-in user), hasRole(...) and hasAnyRole(...).

Every rule ends with what is required. These five lines use one requirement each; the program then calls ShopLite as three different callers.

Java
.requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll()      // anyone.requestMatchers("/api/v1/me/**").hasRole("CUSTOMER")                    // one role.requestMatchers(HttpMethod.POST, "/api/v1/orders/*/cancel")    .hasAnyRole("CUSTOMER", "ADMIN")                                     // either role.requestMatchers("/api/v1/profile").authenticated()                      // any signed-in user.anyRequest().denyAll()                                                  // nobody

Example 2 · Every rule against three callers

Runs in: the shoplite-api Spring Boot project

Terminal
# matrix.sh: logs in as Asha and as the admin, then calls each request three times:# with no token, with Asha's token and with the admin's token, and prints the status codes.ASHA=$(login asha.rao@example.com asha-dev-password)ADMIN=$(login admin@shoplite.example shoplite-admin-dev)call GET   /api/v1/products/6call PATCH /api/v1/products/6 '{"price": 1199.00}'call GET   /api/v1/me/orderscall GET   /api/v1/orders/14call GET   /api/v1/reports# ... one call per row below
Output
REQUEST                                        guest   asha  admin
GET /api/v1/products/6                           200    200    200
PATCH /api/v1/products/6                         401    403    200
GET /api/v1/products?includeInactive=true        401    403    200
GET /api/v1/me/orders                            401    200    403
GET /api/v1/orders/1                             401    200    200
GET /api/v1/orders/14                            401    404    200
GET /api/v1/orders/14/items                      401    404    200
POST /api/v1/orders/14/cancel                    401    404    409
POST /api/v1/orders/14/ship                      401    403    409
GET /api/v1/orders                               401    403    200
GET /api/v1/customers/1                          401    403    200
GET /api/v1/reports                              401    403    403
GET /api/v1/orders/14/                           401    403    404

What this code does

  • The same URL gives 401, 403 or 200 depending only on who calls: 401 means "no token", 403 means "known, but not allowed".
  • /me/orders is customer-only, so the admin gets 403. /orders/14 passes the URL rule for Asha but OrderService answers 404: it is Ravi's order (the Owner checks lesson).
  • /api/v1/reports does not exist and no rule names it, so denyAll() answers before Spring even looks for a controller.

When a rule refuses, the answer depends on who asked. A caller with no token (Spring calls them anonymous) gets 401: sign in first. A signed-in caller without the right role gets 403: signing in again will not help.

ShopLite does not use authenticated(): every signed-in rule names its roles, so a new role (say a delivery partner) gets nothing until someone decides what it may do.

Predict the output

Which status code?

Read the rule and the caller, then pick the status code.

Round 1 of 4

The admin calls GET /api/v1/me/orders.

// request: GET /api/v1/me/orders, caller: admin
.requestMatchers("/api/v1/me/**").hasRole("CUSTOMER")

Rule order and a deny-by-default last rule

Deny by default means the last rule is anyRequest().denyAll(): any path that no rule above mentions is refused. The API fails closed, not open, when someone adds an endpoint and forgets the security table.

Spring checks rules from top to bottom, and the first match decides. Here a broad admin rule sits above the public one, so even guests lose the catalogue.

Example 3 · A broad rule placed too early

Runs in: the shoplite-api Spring Boot project

Java
.authorizeHttpRequests(auth -> auth    .requestMatchers(HttpMethod.POST, "/api/v1/auth/**").permitAll()    // WRONG: this matches GET too, and it comes first    .requestMatchers("/api/v1/products/**", "/api/v1/categories/**").hasRole("ADMIN")    .requestMatchers(HttpMethod.GET, "/api/v1/products/**", "/api/v1/categories/**").permitAll()    .anyRequest().denyAll())
Sample output
$ curl -i http://localhost:8080/api/v1/products/6
HTTP/1.1 401
WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Sign in to use this endpoint.","instance":"/api/v1/products/6"}

$ curl -i http://localhost:8080/api/v1/products/6 -H "Authorization: Bearer $ASHA"
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/products/6"}

What this code does

  • The admin rule matches GET /api/v1/products/6 first, so the public rule below it is never reached.
  • The app starts without any warning; the mistake shows up only as wrong status codes.
  • Fix: move the GET ... permitAll() line above the admin line, as in Example 1, and keep a test that a guest can read a product.

The first matching rule decides, so specific rules go first and broad rules last. The last rule is anyRequest().denyAll(): a guest asking for a path no rule mentions gets 401, and even an admin gets 403.

Order of execution

Put the rules in order

Tap the three rules in the order they must be written.

Spring Security 7 refuses to start if anyRequest() is not the last rule: you cannot accidentally put rules after it.

Path pattern pitfalls: trailing slashes, * vs **, forgotten endpoints

A path pattern describes which URL paths a rule matches. * matches exactly one segment and ** matches the rest of the path, so /orders/* matches /orders/14 but not /orders/14/items.

ShopLite lists /api/v1/orders/*/items as well as /api/v1/orders/*, and a trailing slash counts as a different path. These two requests show what that does.

Example 4 · A trailing slash falls through to another rule

Runs in: the shoplite-api Spring Boot project

Terminal
curl -i http://localhost:8080/api/v1/orders/14/ -H "Authorization: Bearer $ASHA"curl -i http://localhost:8080/api/v1/orders/14/ -H "Authorization: Bearer $ADMIN"
Output
HTTP/1.1 403 
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/orders/14/"}

HTTP/1.1 404 
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"No static resource api/v1/orders/14.","instance":"/api/v1/orders/14/"}

What this code does

  • For Asha, /orders/14/ does not match "/api/v1/orders/*", so the next matching rule, "/api/v1/orders/**" (admin only), refuses her with 403.
  • The admin passes that rule, but no controller maps the path with a slash, so Spring answers 404. (Security headers trimmed.)
  • Neither request reaches OrderController, so the slash cannot be used to slip past the owner check; it only gives confusing answers.

Trailing slashes are separate paths in Spring Framework 7: /api/v1/orders/14/ does not match "/api/v1/orders/*", and no controller handles it either. Clients should send the URL exactly as the contract writes it.

"/api/v1/orders/**" matches /api/v1/orders itself, /14, /14/items and anything deeper. A forgotten endpoint is the third pitfall, and denyAll() closes it: a new GET /api/v1/reports stays closed until someone adds a rule on purpose.

Testing URL rules: @WithMockUser and jwt()

jwt() is a Spring Security test helper that attaches a made-up JWT to one MockMvc request, with the claims and authorities you choose. It skips real login and signatures, so you test the rules, not the token code.

A @WebMvcTest loads only the web layer, so every service is a mock. This test calls the URL rules as a guest, as Asha and as the admin, and checks only the status codes.

Example 5 · src/test/java/com/shoplite/common/security/SecurityRulesTest.java

Runs in: the shoplite-api Spring Boot project

Java
package com.shoplite.common.security;
import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.BDDMockito.given;import static org.mockito.Mockito.verifyNoInteractions;import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import java.math.BigDecimal;import java.util.List;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.oauth2.jwt.JwtDecoder;import org.springframework.security.test.context.support.WithMockUser;import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.JwtRequestPostProcessor;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.assertj.MockMvcTester;
import com.shoplite.auth.TokenService;import com.shoplite.category.CategoryService;import com.shoplite.common.PageResponse;import com.shoplite.customer.CustomerService;import com.shoplite.order.OrderService;import com.shoplite.product.ProductResponse;import com.shoplite.product.ProductService;import com.shoplite.user.UserService;
/** The URL rules in SecurityConfig for a guest, a customer and an admin. No database, no real tokens. */@WebMvcTest@Import({ SecurityConfig.class, ProblemAuthenticationEntryPoint.class, ProblemAccessDeniedHandler.class,          SecurityProblemWriter.class })class SecurityRulesTest {
    private static final String PRICE_PATCH = "{\"price\": 1199.00}";    private static final ProductResponse AIRDOPES = new ProductResponse(6, "ACC-AD141", "boAt Airdopes 141",            4, "Accessories", new BigDecimal("1199.00"), 120, true);
    @Autowired    private MockMvcTester mvc;
    @MockitoBean private ProductService productService;    @MockitoBean private CategoryService categoryService;    @MockitoBean private CustomerService customerService;    @MockitoBean private OrderService orderService;    @MockitoBean private UserService userService;    @MockitoBean private TokenService tokenService;    @MockitoBean private UserDetailsService userDetailsService;    @MockitoBean private JwtDecoder jwtDecoder;
    /** Asha: user 2, customer 1. jwt() skips our converter, so the authorities are set by hand. */    private static JwtRequestPostProcessor asha() {        return jwt().jwt(token -> token.subject("2").claim("roles", List.of("CUSTOMER")).claim("customerId", 1))                .authorities(new SimpleGrantedAuthority("ROLE_CUSTOMER"));    }
    private static JwtRequestPostProcessor admin() {        return jwt().jwt(token -> token.subject("1").claim("roles", List.of("ADMIN")))                .authorities(new SimpleGrantedAuthority("ROLE_ADMIN"));    }
    @Test    void guestCanBrowseTheCatalogue() {        given(productService.get(6)).willReturn(AIRDOPES);
        assertThat(mvc.get().uri("/api/v1/products/6")).hasStatusOk();    }
    @Test    void guestGets401WithAProblemBody() {        assertThat(mvc.patch().uri("/api/v1/products/6").contentType(MediaType.APPLICATION_JSON).content(PRICE_PATCH))                .hasStatus(HttpStatus.UNAUTHORIZED)                .satisfies(result -> assertThat(result.getResponse().getHeader("WWW-Authenticate")).startsWith("Bearer"))                .bodyJson().extractingPath("$.type").isEqualTo("https://shoplite.example/problems/unauthorized");        verifyNoInteractions(productService);               // the controller was never reached    }
    @Test    void customerGets403ForCatalogueChanges() {        assertThat(mvc.patch().uri("/api/v1/products/6").with(asha())                .contentType(MediaType.APPLICATION_JSON).content(PRICE_PATCH))                .hasStatus(HttpStatus.FORBIDDEN)                .bodyJson().extractingPath("$.type").isEqualTo("https://shoplite.example/problems/forbidden");        verifyNoInteractions(productService);    }
    @Test    void adminCanChangeTheCatalogue() {        given(productService.patch(eq(6), any())).willReturn(AIRDOPES);
        assertThat(mvc.patch().uri("/api/v1/products/6").with(admin())                .contentType(MediaType.APPLICATION_JSON).content(PRICE_PATCH))                .hasStatusOk();    }
    @Test    void meIsForCustomersOnly() {        given(orderService.search(eq(1), any(), any(), eq(0), eq(20)))                .willReturn(PageResponse.of(List.of(), 0, 20, 0));
        assertThat(mvc.get().uri("/api/v1/me/orders").with(asha())).hasStatusOk();        assertThat(mvc.get().uri("/api/v1/me/orders").with(admin())).hasStatus(HttpStatus.FORBIDDEN);        assertThat(mvc.get().uri("/api/v1/me/orders")).hasStatus(HttpStatus.UNAUTHORIZED);    }
    @Test    void customersCannotListAllOrdersOrShip() {        assertThat(mvc.get().uri("/api/v1/orders").with(asha())).hasStatus(HttpStatus.FORBIDDEN);        assertThat(mvc.post().uri("/api/v1/orders/15/ship").with(asha())).hasStatus(HttpStatus.FORBIDDEN);        verifyNoInteractions(orderService);    }
    @Test    void anEndpointNobodyListedIsDenied() {        assertThat(mvc.get().uri("/api/v1/reports")).hasStatus(HttpStatus.UNAUTHORIZED);        assertThat(mvc.get().uri("/api/v1/reports").with(admin())).hasStatus(HttpStatus.FORBIDDEN);    }
    @Test    @WithMockUser(roles = "ADMIN")    void withMockUserIsEnoughForRulesThatOnlyNeedARole() {        assertThat(mvc.get().uri("/api/v1/customers/1")).hasStatusOk();    }}
Sample output
$ ./mvnw test
...
[INFO] Running com.shoplite.common.security.SecurityRulesTest
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 27.66 s -- in com.shoplite.common.security.SecurityRulesTest
[INFO]
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

What this code does

  • asha() and admin() build requests with made-up tokens; .authorities(...) is needed because jwt() skips ShopLite's converter.
  • @MockitoBean replaces every service and the JwtDecoder, so the test needs no database and no secret; it checks only the rules and the error bodies.
  • The last test shows @WithMockUser is enough when the controller does not read the token, like GET /api/v1/customers/1.

@WithMockUser(roles = "ADMIN") runs a whole test as a made-up signed-in user with ROLE_ADMIN. Use jwt() when the controller reads the token, such as /me/orders, which needs the customerId claim.

One catch: jwt() does not run your JwtAuthenticationConverter. Its authorities come from the scope claim unless you set them with .authorities(new SimpleGrantedAuthority("ROLE_CUSTOMER")), as the test does.

Next step

Check your understanding

12 quick questions