We can configure multiple HttpSecurity instances just as we can have multiple <http>
blocks. The key is to extend the WebSecurityConfigurerAdapter
multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/
.
@EnableWebSecurity public class MultiHttpSecurityConfig { @Bean public UserDetailsService userDetailsService() throws Exception { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withUsername("user").password("password").roles("USER").build()); manager.createUser(User.withUsername("admin").password("password").roles("USER","ADMIN").build()); return manager; } @Configuration @Order(1) 1 public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") 2 .authorizeRequests() .anyRequest().hasRole("ADMIN") .and() .httpBasic(); } } @Configuration 3 public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } } }
Configure Authentication as normal
1、Create an instance of WebSecurityConfigurerAdapter that contains @Order to specify which WebSecurityConfigurerAdapter should be considered first.
2、The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/
3、Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This configuration is considered after
ApiWebSecurityConfigurationAdapter since it has an @Order value after 1 (no @Order defaults to last).