Spring Security(十六):5.7 Multiple HttpSecurity
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.
建立包含@Order的WebSecurityConfigurerAdapter例項,以指定應首先考慮哪個WebSecurityConfigurerAdapter。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).
建立WebSecurityConfigurerAdapter的另一個例項。如果URL不以/ api /開頭,則將使用此配置。此配置在ApiWebSecurityConfigurationAdapter之後考慮,因為它在1之後具有@Order值(沒有@Order預設為last)。