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/.

我们可以配置多个HttpSecurity实例,就像我们可以有多个<http>块一样。关键是多次扩展WebSecurityConfigurerAdapter。例如,以下是具有以/ api /开头的URL的不同配置的示例。
 
@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/

http.antMatcher声明此HttpSecurity仅适用于以/ api /开头的URL

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)。

猜你喜欢

转载自www.cnblogs.com/shuaiandjun/p/10134326.html