【个人版】SpringBoot下Spring-Security核心概念解读【一】
SpringBoot + Spring-Security + FilterChainProxy
Spring-Security全局导读:
1、Security核心类设计
2、HttpSecurity结构和执行流程解读
3、Spring-Security个人落地篇
背景: 凡项目内存在与外部系统交互,基本安全校验少不了。因项目规模与框架发展原因,历史项目中很多时候直接在Filter中完成安全校验(HandlerInterceptor同理),基本需求完全够用。现在因微服务、中心化等原因,自己写权限管理逻辑代码量较多,后期修改工作量可能较大,所以spring全家桶中的安全框架spring-security随SpringBoot发展而热门起来。最近走读源码,发现spring-security其实还是以Filter为基础,只是把周边功能及场景通过逻辑封装,进而成为开箱即用的安全框架。
Spring-Securiy的核心类是FilterChainProxy,FilterChainProxy的顶层接口是Filter
所以只要理解了FilterChainProxy类的架构设计、构建流程、执行细节,那么这个框架基本就了解了。关于Filter的深入理解,可以看之前解读:
Filter系列解读:
1、SpringBoot下Filter自动适配
2、SpringBoot下Filter注册流程
3、Filter链式执行设计解读
下面直接上FilterChainProxy二改版源码:
public class org.springframework.security.web.FilterChainProxy extends GenericFilterBean implements Filter, BeanNameAware, EnvironmentAware, EnvironmentCapable, ServletContextAware, InitializingBean, DisposableBean{
// 鉴权过滤器链,根据请求匹配,一般一个(匹配/*)就足够,除非网关类项目且鉴权逻辑差异较大
private List<SecurityFilterChain> filterChains;
// 请求包装类,授权框架处理定制版
private HttpFirewall firewall;
// SecurityFilterChain就是spring-security封装的权限处理类,其内部核心就是鉴权Filter
// SecurityFilterChain的定义、生成流程及逻辑后续篇说明
public FilterChainProxy(List<SecurityFilterChain> filterChains) {
this.firewall = new StrictHttpFirewall();
this.filterChains = filterChains;
}
// FilterChainProxy本身就是Filter,且url pattern为/*,所有请求都会在此进入执行
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
this.doFilterInternal(request, response, chain);
} catch (Exception var11) {
// 异常处理,此处忽略
} finally {
SecurityContextHolder.clearContext();
request.removeAttribute(FILTER_APPLIED);
}
}
private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 请求响应预包装,可不关注
FirewalledRequest firewallRequest = this.firewall.getFirewalledRequest((HttpServletRequest)request);
HttpServletResponse firewallResponse = this.firewall.getFirewalledResponse((HttpServletResponse)response);
// 这里根据请求URI匹配对应SecurityFilterChain,进而获取其包装的【鉴权相关】Filter集合
List<Filter> filters = this.getFilters((HttpServletRequest)firewallRequest);
if (filters != null && filters.size() != 0) {
// 将参数chain和filters用内部类封装成新的FilterChain,使执行流程完全等同于普通过滤器
VirtualFilterChain virtualFilterChain = new VirtualFilterChain(firewallRequest, chain, filters);
// 内部定义FilterChain执行入口
virtualFilterChain.doFilter(firewallRequest, firewallResponse);
} else {
firewallRequest.reset();
// 无权限处理相关类,执行外部过滤器链的下一个,直接忽略FilterChainProxy过滤器
chain.doFilter(firewallRequest, firewallResponse);
}
}
// 通过请求获取鉴权过滤器列表,逻辑较为简单
private List<Filter> getFilters(HttpServletRequest request) {
int count = 0;
Iterator var3 = this.filterChains.iterator();
SecurityFilterChain chain;
do {
if (!var3.hasNext()) {
return null;
}
chain = (SecurityFilterChain)var3.next();
} while(!chain.matches(request));
// 根据匹配到的SecurityFilterChain,返回其包含的所有Filter
return chain.getFilters();
}
//VirtualFilterChain可类比ApplicationFilterChain,此设计极高解耦代码执行流程
private static final class VirtualFilterChain implements FilterChain {
// 保存原始chain对象,执行完所有授权Filter后,继续执行原始链的下一个过滤器
private final FilterChain originalChain;
// 授权过滤器集合
private final List<Filter> additionalFilters;
private final FirewalledRequest firewalledRequest;
// 鉴权过滤器总数
private final int size;
// 当前过滤器执行位置索引
private int currentPosition;
private VirtualFilterChain(FirewalledRequest firewalledRequest, FilterChain chain, List<Filter> additionalFilters) {
this.currentPosition = 0;
this.originalChain = chain;
this.additionalFilters = additionalFilters;
this.size = additionalFilters.size();
this.firewalledRequest = firewalledRequest;
}
// 此块逻辑完美体现数组 + Filter类设计的美感
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if (this.currentPosition == this.size) {
// 授权过滤器执行完成
this.firewalledRequest.reset();
this.originalChain.doFilter(request, response);
} else {
// 循环做权限上下文中的所有检查及鉴权操作,注意索引自增
Filter nextFilter = (Filter)this.additionalFilters.get(this.currentPosition++);
nextFilter.doFilter(request, response, this);
}
}
}
}
FilterChainProxy的核心代码及相关介绍已在上面具体标注了,框架帮我们把业务无关的代码全部封装起来,我们只需要关注核心的鉴权管理,剩下的全交给框架了。
除了FilterChainProxy源码解读,还有几个问题需要弄明白:
1、FilterChainProxy作为过滤器,是怎么注册到Spring容器的?和普通过滤器注册是否不同?
2、FilterChainProxy作为过滤器,有没有优先级要求?
3、我们自定义的鉴权类过滤器,是否会影响ApplicationFilterChain原始链的执行?
4、security框架,为我们封装了哪些内部过滤器?
5、我们定义的普通过滤器,会自动添加到授权过滤器列表吗?
FilterChainProxy注册:
@Configuration(
proxyBeanMethods = false
)
public class org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration implements ImportAware, BeanClassLoaderAware {
@Bean(
name = {"springSecurityFilterChain"}
)
public Filter springSecurityFilterChain() throws Exception {
boolean hasConfigurers = this.webSecurityConfigurers != null && !this.webSecurityConfigurers.isEmpty();
boolean hasFilterChain = !this.securityFilterChains.isEmpty();
Iterator var7 = this.securityFilterChains.iterator();
while(true) {
while(var7.hasNext()) {
SecurityFilterChain securityFilterChain = (SecurityFilterChain)var7.next();
this.webSecurity.addSecurityFilterChainBuilder(() -> {
return securityFilterChain;
});
Iterator var5 = securityFilterChain.getFilters().iterator();
while(var5.hasNext()) {
Filter filter = (Filter)var5.next();
if (filter instanceof FilterSecurityInterceptor) {
this.webSecurity.securityInterceptor((FilterSecurityInterceptor)filter);
break;
}
}
}
var7 = this.webSecurityCustomizers.iterator();
while(var7.hasNext()) {
WebSecurityCustomizer customizer = (WebSecurityCustomizer)var7.next();
customizer.customize(this.webSecurity);
}
return (Filter)this.webSecurity.build();
}
}
}
@Autowired(
required = false
)
void setFilterChains(List<SecurityFilterChain> securityFilterChains) {
this.securityFilterChains = securityFilterChains;
}
protected Filter performBuild() throws Exception {
int chainSize = this.ignoredRequests.size() + this.securityFilterChainBuilders.size();
List<SecurityFilterChain> securityFilterChains = new ArrayList(chainSize);
List<RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>>> requestMatcherPrivilegeEvaluatorsEntries = new ArrayList();
var4 = this.securityFilterChainBuilders.iterator();
while(var4.hasNext()) {
SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder = (SecurityBuilder)var4.next();
SecurityFilterChain securityFilterChain = (SecurityFilterChain)securityFilterChainBuilder.build();
securityFilterChains.add(securityFilterChain);
requestMatcherPrivilegeEvaluatorsEntries.add(this.getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
}
FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);
Filter result = filterChainProxy;
this.postBuildAction.run();
return (Filter)result;
}
重点:
1、securityFilterChains由外部实例化后,注入到该配置类中【列表注入】
2、SecurityFilterChain由HttpSecurity类构建而来,WebSecurity构建结果为FilterChainProxy
3、FilterSecurityInterceptor负责安全检查,未授权请求在此拒绝
4、FilterSecurityInterceptor在SecurityFilterChain的Filter列表中最后一个
我们知道过滤器真正执行是否两块逻辑组成:Filter实例 + 匹配|执行元数据,所以在过去spring时代我们通常需要FilterRegistrationBean完成注册。元数据关系到过滤器执行的时机及顺序,这块在哪里配置的呢?
@ConfigurationProperties(
prefix = "spring.security"
)
public class SecurityProperties {
public static final int BASIC_AUTH_ORDER = 2147483642;
public static final int IGNORED_ORDER = Integer.MIN_VALUE;
public static final int DEFAULT_FILTER_ORDER = -100;
private final Filter filter = new Filter();
private final User user = new User();
public static class Filter {
private int order = -100;
private Set<DispatcherType> dispatcherTypes;
public Filter() {
this.dispatcherTypes = new HashSet(Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST));
}
}
}
@EnableConfigurationProperties({SecurityProperties.class})
public class org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration {
@Bean
@ConditionalOnBean(
name = {"springSecurityFilterChain"}
)
public DelegatingFilterProxyRegistrationBean securityFilterChainRegistration(SecurityProperties securityProperties) {
DelegatingFilterProxyRegistrationBean registration = new DelegatingFilterProxyRegistrationBean("springSecurityFilterChain", new ServletRegistrationBean[0]);
registration.setOrder(securityProperties.getFilter().getOrder());
registration.setDispatcherTypes(this.getDispatcherTypes(securityProperties));
return registration;
}
}
说明:
1、配置文件中,以spring.security前缀可配置security过滤器顺序
2、过滤器默认优先级为-100,我们自定义过滤器不要设置负数,负数留给其他框架提前预处理
3、Filter封装类不是FilterRegistrationBean,DelegatingFilterProxyRegistrationBean延迟了FilterChainProxy的实例化,为自定义配置执行留下较大的配置事件
4、通过RegistrationBean,我们在处理请求时,就可以在原始ApplicationFilterChain链的靠前位置执行鉴权逻辑了
5、一般我们在Filter获取Request对象的实际类型时,基本都是RequestFacade类型,但当使用security框架后,我们接收到的可能是其他请求Wrapper类型,这时候如果自定义Filter存在Request类型的反射处理,就会报错了。
以下为security框架自带的部分Filter清单:
DisableEncodeUrlFilter
WebAsyncManagerlntegrationFilter
SecurityContextPersistenceFilter // 上下文管理
HeaderWriterFilter
CsrfFilter // 防止Csrf攻击,网关/多端类根据需要关闭
LogoutFilter //退出管理
UsernamePasswordAuthenticationFilter //核心,用户名及密码验证
DefaultLoginPageGeneratingFilter
DefaultLogoutPageGeneratingFilter
BasicAuthenticationFilter // Basic授权管理
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter // Session会话管理
ExceptionTranslationFilter
FilterSecurityInterceptor // 授权状态检查,最后兜底关口
解答最后两个问题:
3、我们自定义的鉴权类过滤器,是否会影响ApplicationFilterChain原始链的执行?
---- 自定义Security框架Filter不会影响原始链执行,但是也会在ApplicationFilterChain保存一份,只不过doFilter方法检测无需处理。我们自定义权限过滤器肯定是处理某一登录场景,URL是固定值。
5、我们定义的普通过滤器,会自动添加到授权过滤器列表吗?
---- 不会,授权过滤器链内容由HttpSecurity构建,除非我们手工将Filter添加到配置上下文中,否则只会在原始ApplicationFilterChain出现。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!