Both security filter chains are not restricted (default is /**
).
Spring Security 6
You have to restrict the first one with securityMatcher
, see Spring Security Reference:
Multiple HttpSecurity Instances
We can configure multiple
HttpSecurity
instances just as we can have multiple<http>
blocks in XML. The key is to register multipleSecurityFilterChain
@Beans
. The following example has a different configuration for URL’s that start with/api/
.@Configuration @EnableWebSecurity public class MultiHttpSecurityConfig { @Bean public UserDetailsService userDetailsService() throws Exception { // ensure the passwords are encoded properly UserBuilder users = User.withDefaultPasswordEncoder(); InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(users.username("user").password("password").roles("USER").build()); manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build()); return manager; } @Bean @Order(1) public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { http .securityMatcher("/api/**") .authorizeHttpRequests(authorize -> authorize .anyRequest().hasRole("ADMIN") ) .httpBasic(withDefaults()); return http.build(); } @Bean public SecurityFilterChain formLoginFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .formLogin(withDefaults()); return http.build(); } }
- Configure Authentication as usual.
- Create an instance of
SecurityFilterChain
that contains@Order
to specify whichSecurityFilterChain
should be considered first.- The
http.securityMatcher
states that thisHttpSecurity
is applicable only to URLs that start with/api/
.- Create another instance of
SecurityFilterChain
. If the URL does not start with/api/
, this configuration is used. This configuration is considered afterapiFilterChain
, since it has an@Order
value after1
(no@Order
defaults to last).