Spring Security文档Java Configuration一节虽然给出了配置的指导,但还不够深入,下面具体说明配置的生效过程。
@EnableWebSecurity注解
@EnableWebSecurity注解显式启用了Spring Security,其代码如下:
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
SpringWebMvcImportSelector.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
/**
* Controls debugging support for Spring Security. Default is false.
* @return if true, enables debug support with Spring Security
*/
boolean debug() default false;
}
- 看源码@EnableWebSecurity不需要和@Configuration一起使用,因为@EnableWebSecurity已经包括了@Configuration;
- 导入了WebSecurityConfiguration配置类和SpringWebMvcImportSelector。
WebSecurityConfiguration配置类
WebSecurityConfiguration配置类利用WebSecurity创建FilterChainProxy,其成员变量如下:
@Configuration
public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAware {
private WebSecurity webSecurity;
private Boolean debugEnabled;
private List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers;
private ClassLoader beanClassLoader;
}
- webSecurity保存要配置的WebSecurity对象;
- webSecurityConfigurers保存当前上下文中所有的WebSecurityConfigurer。
获取当前上下文中的所有WebSecurityConfigurer是通过autowiredWebSecurityConfigurersIgnoreParents方法实现的:
@Bean
public AutowiredWebSecurityConfigurersIgnoreParents autowiredWebSecurityConfigurersIgnoreParents(
ConfigurableListableBeanFactory beanFactory) {
return new AutowiredWebSecurityConfigurersIgnoreParents(beanFactory);
}
- 该方法实例化一个AutowiredWebSecurityConfigurersIgnoreParents类型的bean,该类的getWebSecurityConfigurers返回当前上下文中的所有WebSecurityConfigurer。
setFilterChainProxySecurityConfigurer方法用到了上一个方法,从第二个参数的@Value可以看到当前上下文中的所有WebSecurityConfigurer会被注入到参数中:
@Autowired(required = false)
public void setFilterChainProxySecurityConfigurer(
ObjectPostProcessor<Object> objectPostProcessor,
@Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers)
throws Exception {
webSecurity = objectPostProcessor
.postProcess(new WebSecurity(objectPostProcessor));
if (debugEnabled != null) {
webSecurity.debug(debugEnabled);
}
Collections.sort(webSecurityConfigurers, AnnotationAwareOrderComparator.INSTANCE);
Integer previousOrder = null;
Object previousConfig = null;
for (SecurityConfigurer<Filter, WebSecurity> config : webSecurityConfigurers) {
Integer order = AnnotationAwareOrderComparator.lookupOrder(config);
if (previousOrder != null && previousOrder.equals(order)) {
throw new IllegalStateException(
"@Order on WebSecurityConfigurers must be unique. Order of "
+ order + " was already used on " + previousConfig + ", so it cannot be used on "
+ config + " too.");
}
previousOrder = order;
previousConfig = config;
}
for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {
webSecurity.apply(webSecurityConfigurer);
}
this.webSecurityConfigurers = webSecurityConfigurers;
}
- webSecurity成员变量保存新实例化的WebSecurity;
- 对当前上下文中所有的WebSecurityConfigurer进行升序排序;
- 将排序后的所有WebSecurityConfigurer依次添加到WebSecurity中;
- webSecurityConfigurers成员变量保存排序后的所有WebSecurityConfigurer。
springSecurityFilterChain方法创建了Spring Security的过滤器链:
/**
* Creates the Spring Security Filter Chain
* @return
* @throws Exception
*/
@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public Filter springSecurityFilterChain() throws Exception {
boolean hasConfigurers = webSecurityConfigurers != null
&& !webSecurityConfigurers.isEmpty();
if (!hasConfigurers) {
WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor
.postProcess(new WebSecurityConfigurerAdapter() {
});
webSecurity.apply(adapter);
}
return webSecurity.build();
}
- @Bean注解指定新实例化的bean的名称是springSecurityFilterChain;
- hasConfigurers判断是为了处理这样一种情况,如果用户没有实现WebSecurityConfigurer接口的类,那么当前上下文就不会有WebSecurityConfigurer,这时就使用WebSecurityConfigurerAdapter类中的默认值;
- WebSecurity的构建产出是过滤器。
- 这里我有个疑问:setFilterChainProxySecurityConfigurer方法的setter注入一定先于springSecurityFilterChain执行吗?其实根据日常编程的经验,配置类中@Autowired注入一定先于@Bean注解方法执行,因为有些@Bean方法会用到@Autowired注入的单例,真正的证据还应该去看相关源码。
WebSecurityConfigurer接口
上文提到WebSecurityConfiguration配置类会查找当前上下文中所有的WebSecurityConfigurer,本节分析WebSecurityConfigurer。
WebSecurityConfigurer是一个接口,继承了SecurityConfigurer接口,它们都使用了泛型。
public interface SecurityConfigurer<O, B extends SecurityBuilder<O>> {
void init(B builder) throws Exception;
void configure(B builder) throws Exception;
}
public interface SecurityBuilder<O> {
O build() throws Exception;
}
public interface WebSecurityConfigurer<T extends SecurityBuilder<Filter>> extends
SecurityConfigurer<Filter, T> {
}
- SecurityConfigurer接口中,泛型参数B表示一种SecurityBuilder,泛型参数O表示B的构建输出;
- SecurityBuilder的种类很多,常见的有WebSecurity和HttpSecurity,该接口只有一个build方法用来输出构建结果;
- WebSecurityConfigurer接口表示SecurityBuilder的构建输出是Filter。
- 实际自定义配置时很少会直接编写WebSecurityConfigurer接口的实现类,都是继承WebSecurityConfigurerAdapter类并覆盖某几个方法,如configure(WebSecurity)方法配置全局安全,configure(HttpSecurity)方法配置各具体的过滤器。
HttpSecurity类
HttpSecurity类的部分代码如下,它的构建输出是DefaultSecurityFilterChain,可以用HttpSecurity配置Spring Security的各过滤器。
public final class HttpSecurity extends
AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain, HttpSecurity>
implements SecurityBuilder<DefaultSecurityFilterChain>,
HttpSecurityBuilder<HttpSecurity> {
@Override
protected DefaultSecurityFilterChain performBuild() throws Exception {
Collections.sort(filters, comparator);
return new DefaultSecurityFilterChain(requestMatcher, filters);
}
// 省略一些代码
}
- performBuild方法执行具体的构建过程,requestMatcher和filters都是HttpSecurity的成员变量;
- requestMatcher成员变量可以通过调用antMatcher、mvcMatcher、regexMatcher和requestMatcher方法修改,表示哪些请求需要使用过滤器保护;
- filters成员变量保存所配置的Spring Security过滤器,如SecurityContextPersistenceFilter和LogoutFilter等;
- 各过滤器的配置可以通过HttpSecurity类的对应方法实现,如formLogin方法启用表单认证,对应UsernamePasswordAuthenticationFilter,如果没有指定登录页的话还会配置DefaultLoginPageGeneratingFilter,httpBasic方法启用Basic认证,对应BasicAuthenticationFilter,logout方法配置注销功能,对应LogoutFilter。
WebSecurity类
WebSecurity类的部分代码如下,它的构建输出是Filter,更具体的说是FilterChainProxy。
public final class WebSecurity extends
AbstractConfiguredSecurityBuilder<Filter, WebSecurity> implements
SecurityBuilder<Filter>, ApplicationContextAware {
@Override
protected Filter performBuild() throws Exception {
Assert.state(
!securityFilterChainBuilders.isEmpty(),
"At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. Typically this done by adding a @Configuration that extends WebSecurityConfigurerAdapter. More advanced users can invoke "
+ WebSecurity.class.getSimpleName()
+ ".addSecurityFilterChainBuilder directly");
int chainSize = ignoredRequests.size() + securityFilterChainBuilders.size();
List<SecurityFilterChain> securityFilterChains = new ArrayList<SecurityFilterChain>(
chainSize);
for (RequestMatcher ignoredRequest : ignoredRequests) {
securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest));
}
for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : securityFilterChainBuilders) {
securityFilterChains.add(securityFilterChainBuilder.build());
}
FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);
if (httpFirewall != null) {
filterChainProxy.setFirewall(httpFirewall);
}
filterChainProxy.afterPropertiesSet();
Filter result = filterChainProxy;
if (debugEnabled) {
logger.warn("\n\n"
+ "********************************************************************\n"
+ "********** Security debugging is enabled. *************\n"
+ "********** This may include sensitive information. *************\n"
+ "********** Do not use in a production system! *************\n"
+ "********************************************************************\n\n");
result = new DebugFilter(filterChainProxy);
}
postBuildAction.run();
return result;
}
// 省略一些代码
}
- 与HttpSecurity相似,同样是performBuild方法执行具体的构建过程;
- ignoredRequests成员变量保存需要被忽略的请求,可以通过调用ignoring方法修改。performBuild方法会为每个被忽略的请求都生成一个SecurityFilterChain;
- HttpSecurity接着在该方法里输出一个SecurityFilterChain;
- 这些SecurityFilterChain被用来实例化FilterChainProxy。
Spring Security的过滤器一文提到“FilterChainProxy的getFilters方法根据请求查找第一个匹配的SecurityFilterChain”,所以WebSecurity配置的忽略请求根本不会进到Spring Security的过滤器。
Spring Boot自动配置
Spring Boot中与Spring Security相关的自动配置有两个主要的类:
- SecurityAutoConfiguration:若不使用@EnableWebSecurity注解显式启用Spring Security,那么就会导入SpringBootWebSecurityConfiguration,会使用WebSecurityConfigurerAdapter的默认配置。
- SecurityFilterAutoConfiguration:不管使不使用@EnableWebSecurity注解,该类都会向容器注册一个DelegatingFilterProxy实例,它会代理名为springSecurityFilterChain的bean,即WebSecurityConfiguration配置类生成的FilterChainProxy。DelegatingFilterProxy处于spring-web.jar中,而FilterChainProxy处于spring-security-web.jar,通过以上分析可以感受到DelegatingFilterProxy强大的代理功能。