Spring Security常用过滤器实例解析
SpringSecurity常见的15个拦截器
1.org.springframework.security.web.context.SecurityContextPersistenceFilter
首当其冲的一个过滤器,作用之重要,自不必多言。
- SecurityContextPersistenceFilter主要是使用SecurityContextRepository在session中保存或更新一个
- SecurityContext,并将SecurityContext给以后的过滤器使用,来为后续filter建立所需的上下文。
- SecurityContext中存储了当前用户的认证以及权限信息。
2.org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
此过滤器用于集成SecurityContext到Spring异步执行机制中的WebAsyncManager
3.org.springframework.security.web.header.HeaderWriterFilter
向请求的Header中添加相应的信息,可在http标签内部使用security:headers来控制
4.org.springframework.security.web.csrf.CsrfFilter
csrf又称跨域请求伪造,SpringSecurity会对所有post请求验证是否包含系统生成的csrf的token信息,
如果不包含,则报错。起到防止csrf攻击的效果。
5.org.springframework.security.web.authentication.logout.LogoutFilter
匹配URL为/logout的请求,实现用户退出,清除认证信息。
6.org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
认证操作全靠这个过滤器,默认匹配URL为/login且必须为POST请求。
7.org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
如果没有在配置文件中指定认证页面,则由该过滤器生成一个默认认证页面。
8.org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter
由此过滤器可以生产一个默认的退出登录页面
9.org.springframework.security.web.authentication.www.BasicAuthenticationFilter
此过滤器会自动解析HTTP请求中头部名字为Authentication,且以Basic开头的头信息。
10.org.springframework.security.web.savedrequest.RequestCacheAwareFilter
通过HttpSessionRequestCache内部维护了一个RequestCache,用于缓存HttpServletRequest
11.org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
针对ServletRequest进行了一次包装,使得request具有更加丰富的API
12.org.springframework.security.web.authentication.AnonymousAuthenticationFilter
当SecurityContextHolder中认证信息为空,则会创建一个匿名用户存入到SecurityContextHolder中。
springsecurity为了兼容未登录的访问,也走了一套认证流程,只不过是一个匿名的身份。
13.org.springframework.security.web.session.SessionManagementFilter
SecurityContextRepository限制同一用户开启多个会话的数量
14.org.springframework.security.web.access.ExceptionTranslationFilter
异常转换过滤器位于整个springSecurityFilterChain的后方,用来转换整个链路中出现的异常
15.org.springframework.security.web.access.intercept.FilterSecurityInterceptor
获取所配置资源访问的授权信息,根据SecurityContextHolder中存储的用户信息来决定其是否有权限。
那么,是不是springsecurity一共就这么多过滤器呢?答案是否定的!随着spring-security.xml配置的添加,还
会出现新的过滤器。
那么,是不是springsecurity每次都会加载这些过滤器呢?答案也是否定的!随着spring-security.xml配置的修
改,有些过滤器可能会被去掉。
springsecurity过滤器链加载原理
publicclassDelegatingFilterProxyextendsGenericFilterBean{ @Nullable privateStringcontextAttribute; @Nullable privateWebApplicationContextwebApplicationContext; @Nullable privateStringtargetBeanName; privatebooleantargetFilterLifecycle; @Nullable privatevolatileFilterdelegate;//注:这个过滤器才是真正加载的过滤器 privatefinalObjectdelegateMonitor; //注:doFilter才是过滤器的入口,直接从这看! publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChain filterChain)throwsServletException,IOException{ FilterdelegateToUse=this.delegate; if(delegateToUse==null){ synchronized(this.delegateMonitor){ delegateToUse=this.delegate; if(delegateToUse==null){ WebApplicationContextwac=this.findWebApplicationContext(); if(wac==null){ thrownewIllegalStateException("NoWebApplicationContextfound:no ContextLoaderListenerorDispatcherServletregistered?"); } //第一步:doFilter中最重要的一步,初始化上面私有过滤器属性delegate delegateToUse=this.initDelegate(wac); } this.delegate=delegateToUse; } } //第三步:执行FilterChainProxy过滤器 this.invokeDelegate(delegateToUse,request,response,filterChain); } //第二步:直接看最终加载的过滤器到底是谁 protectedFilterinitDelegate(WebApplicationContextwac)throwsServletException{ //debug得知targetBeanName为:springSecurityFilterChain StringtargetBeanName=this.getTargetBeanName(); Assert.state(targetBeanName!=null,"Notargetbeannameset"); //debug得知delegate对象为:FilterChainProxy Filterdelegate=(Filter)wac.getBean(targetBeanName,Filter.class); if(this.isTargetFilterLifecycle()){ delegate.init(this.getFilterConfig()); } returndelegate; } protectedvoidinvokeDelegate(Filterdelegate,ServletRequestrequest,ServletResponse response,FilterChainfilterChain)throwsServletException,IOException{ delegate.doFilter(request,response,filterChain); } }
第二步debug结果如下:
最终在第三步执行了这个过滤器。
publicclassFilterChainProxyextendsGenericFilterBean{ privatestaticfinalLoglogger=LogFactory.getLog(FilterChainProxy.class); privatestaticfinalStringFILTER_APPLIED= FilterChainProxy.class.getName().concat(".APPLIED"); privateListfilterChains; privateFilterChainProxy.FilterChainValidatorfilterChainValidator; privateHttpFirewallfirewall; //咿!?可以通过一个叫SecurityFilterChain的对象实例化出一个FilterChainProxy对象 //这FilterChainProxy又是何方神圣?会不会是真正的过滤器链对象呢?先留着这个疑问! publicFilterChainProxy(SecurityFilterChainchain){ this(Arrays.asList(chain)); } //又是SecurityFilterChain这家伙!嫌疑更大了! publicFilterChainProxy(List filterChains){ this.filterChainValidator=newFilterChainProxy.NullFilterChainValidator(); this.firewall=newStrictHttpFirewall(); this.filterChains=filterChains; } //注:直接从doFilter看 publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain) throwsIOException,ServletException{ booleanclearContext=request.getAttribute(FILTER_APPLIED)==null; if(clearContext){ try{ request.setAttribute(FILTER_APPLIED,Boolean.TRUE); this.doFilterInternal(request,response,chain); }finally{ SecurityContextHolder.clearContext(); request.removeAttribute(FILTER_APPLIED); } }else{ //第一步:具体操作调用下面的doFilterInternal方法了 this.doFilterInternal(request,response,chain); } } privatevoiddoFilterInternal(ServletRequestrequest,ServletResponseresponse,FilterChain chain)throwsIOException,ServletException{ FirewalledRequestfwRequest= this.firewall.getFirewalledRequest((HttpServletRequest)request); HttpServletResponsefwResponse= this.firewall.getFirewalledResponse((HttpServletResponse)response); //第二步:封装要执行的过滤器链,那么多过滤器就在这里被封装进去了! List filters=this.getFilters((HttpServletRequest)fwRequest); if(filters!=null&&filters.size()!=0){ FilterChainProxy.VirtualFilterChainvfc=new FilterChainProxy.VirtualFilterChain(fwRequest,chain,filters); //第四步:加载过滤器链 vfc.doFilter(fwRequest,fwResponse); }else{ if(logger.isDebugEnabled()){ logger.debug(UrlUtils.buildRequestUrl(fwRequest)+(filters==null?"hasno matchingfilters":"hasanemptyfilterlist")); } fwRequest.reset(); chain.doFilter(fwRequest,fwResponse); } } privateList getFilters(HttpServletRequestrequest){ Iteratorvar2=this.filterChains.iterator(); //第三步:封装过滤器链到SecurityFilterChain中! SecurityFilterChainchain; do{ if(!var2.hasNext()){ returnnull; } chain=(SecurityFilterChain)var2.next(); }while(!chain.matches(request)); returnchain.getFilters(); } }
SecurityFilterChain
最后看SecurityFilterChain,这是个接口,实现类也只有一个,这才是web.xml中配置的过滤器链对象!
publicinterfaceSecurityFilterChain{ booleanmatches(HttpServletRequestrequest); ListgetFilters(); }
publicfinalclassDefaultSecurityFilterChainimplementsSecurityFilterChain{ privatestaticfinalLoglogger=LogFactory.getLog(DefaultSecurityFilterChain.class); privatefinalRequestMatcherrequestMatcher; privatefinalListfilters; publicDefaultSecurityFilterChain(RequestMatcherrequestMatcher,Filter...filters){ this(requestMatcher,Arrays.asList(filters)); } publicDefaultSecurityFilterChain(RequestMatcherrequestMatcher,List filters){ logger.info("Creatingfilterchain:"+requestMatcher+","+filters); this.requestMatcher=requestMatcher; this.filters=newArrayList<>(filters); } publicRequestMatchergetRequestMatcher(){ returnrequestMatcher; } publicList getFilters(){ returnfilters; } publicbooleanmatches(HttpServletRequestrequest){ returnrequestMatcher.matches(request); } @Override publicStringtoString(){ return"["+requestMatcher+","+filters+"]"; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。