Spring Security(十六):5.7 Multiple HttpSecurity

Posted 帅S俊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)。

以上是关于Spring Security(十六):5.7 Multiple HttpSecurity的主要内容,如果未能解决你的问题,请参考以下文章

Grails Spring Security 启动缓慢

Spring Security 和 LDAP MD5 认证

如何将自定义密码编码器添加到 Spring Security?

用的挺顺手的 Spring Security 配置类,居然就要被官方弃用了?

这个 Spring Security 图是啥意思?

如何通过Jqgrig请求发送Spring Security csrf