Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring Security request matchers: order rules and cover the fallback

Last updated: 1 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

Spring Security evaluates request authorization matchers in declaration order and applies the first matching rule. A rule written later cannot repair a broader rule that already matched.

Write the narrow exception first

A service may expose a public health probe while requiring authentication for API reads. Put the exact health path before the API pattern, then make the unmatched fallback explicit. Check which filter chain owns each request before reasoning about its authorization rules: securityMatcher selects a chain, while requestMatchers select rules inside it.

Java
package in.aitrove.receipts;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
class ReceiptHttpSecurity {
    @Bean
    SecurityFilterChain receiptSecurity(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
            .requestMatchers("/actuator/health").permitAll()
            .requestMatchers("/api/receipts/**").authenticated()
            .anyRequest().denyAll());
        http.httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

This policy is illustrative: HTTP Basic sends credentials on requests and must be used only over TLS. It does not decide tenant ownership. An authenticated caller still needs an object-level check before reading a receipt, preferably with tenant ownership in the data query.

Match rules by method as well as path when reads and writes have different policies. Exercise the exact allowed path, a nearby path, a method variant and the unmatched fallback in tests. Strings that appear visually similar can match differently when a servlet path, trailing separator or proxy rewrite changes the effective request path.

Common Mistakes

  • Putting a catch-all authenticated rule before a public health exception.
  • Confusing filter-chain selection with a rule inside the selected chain.
  • Treating authentication as proof that a user owns the requested receipt.
  • Testing only allowed requests and never the denied fallback.

Read next

Security filter chain, tenant authorization, and bearer token trust.

spring
spring-boot
security-matcher-order
Storage details