RegexRequestMatcher applies regular expressions when endpoint authorization needs more precision than ordinary path expressions provide. It can restrict requests by characters, path-variable values, or combinations of values. Because regular expressions are difficult to read, use path expressions first and fall back to regex matching when simpler patterns cannot express the rule. section 8.3
Configure the matcher as part of request authorization:
- Pass a RegexRequestMatcher implementation to requestMatchers(), or configure regex matching in the authorization rules. section 8.3
- Match an email path variable so that only addresses ending in .com are permitted. section 8.3
- Match country and language segments so authenticated users can access video from selected countries or in English. section 8.3
Country and language authorization
A /video/{country}/{language} endpoint uses a regular expression to permit authenticated users from the United States, Canada, or the United Kingdom, while also permitting English-language requests. A French request from an ordinary user is forbidden, whereas a premium user is allowed. section 8.3
Listing 8.13 The configuration class using a regex matcher
@Configuration
public class ProjectConfig {
@Bean
public UserDetailsService userDetailsService() {
var uds = new InMemoryUserDetailsManager();
var u1 = User.withUsername("john")
.password("12345")
.authorities("read")
.build();
var u2 = User.withUsername("jane")
.password("12345")
.authorities("read", "premium")
.build();
uds.createUser(u1);
uds.createUser(u2);
return uds;
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http.httpBasic(Customizer.withDefaults());
http.authorizeHttpRequests(
c -> c.regexMatchers(".*/(us|uk|ca)+/(en|fr).*") #1
.authenticated()
.anyRequest()
.hasAuthority("premium"); #2
);
}
}
Inspect the complete Java security configuration that defines users, HTTP Basic authentication, and the regex-based authorization rule. section 8.3
