溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Security常用過(guò)濾器實(shí)例解析

發(fā)布時(shí)間:2020-10-23 10:16:50 來(lái)源:腳本之家 閱讀:214 作者:天宇軒-王 欄目:編程語(yǔ)言

Spring Security常見(jiàn)的15個(gè)攔截器

1 . org.springframework.security.web.context.SecurityContextPersistenceFilter

首當(dāng)其沖的一個(gè)過(guò)濾器,作用之重要,自不必多言。

  • SecurityContextPersistenceFilter主要是使用SecurityContextRepository在session中保存或更新一個(gè)
  • SecurityContext,并將SecurityContext給以后的過(guò)濾器使用,來(lái)為后續(xù)filter建立所需的上下文。
  • SecurityContext中存儲(chǔ)了當(dāng)前用戶的認(rèn)證以及權(quán)限信息。

2 . org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter

此過(guò)濾器用于集成SecurityContext到Spring異步執(zhí)行機(jī)制中的WebAsyncManager

3 . org.springframework.security.web.header.HeaderWriterFilter

向請(qǐng)求的Header中添加相應(yīng)的信息,可在http標(biāo)簽內(nèi)部使用security:headers來(lái)控制

4 . org.springframework.security.web.csrf.CsrfFilter

csrf又稱跨域請(qǐng)求偽造,SpringSecurity會(huì)對(duì)所有post請(qǐng)求驗(yàn)證是否包含系統(tǒng)生成的csrf的token信息,

如果不包含,則報(bào)錯(cuò)。起到防止csrf攻擊的效果。

5. org.springframework.security.web.authentication.logout.LogoutFilter

匹配 URL為/logout的請(qǐng)求,實(shí)現(xiàn)用戶退出,清除認(rèn)證信息。

6 . org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

認(rèn)證操作全靠這個(gè)過(guò)濾器,默認(rèn)匹配URL為/login且必須為POST請(qǐng)求。

7 . org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter

如果沒(méi)有在配置文件中指定認(rèn)證頁(yè)面,則由該過(guò)濾器生成一個(gè)默認(rèn)認(rèn)證頁(yè)面。

8 . org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter

由此過(guò)濾器可以生產(chǎn)一個(gè)默認(rèn)的退出登錄頁(yè)面

9 . org.springframework.security.web.authentication.www.BasicAuthenticationFilter

此過(guò)濾器會(huì)自動(dòng)解析HTTP請(qǐng)求中頭部名字為Authentication,且以Basic開(kāi)頭的頭信息。

10 . org.springframework.security.web.savedrequest.RequestCacheAwareFilter

通過(guò)HttpSessionRequestCache內(nèi)部維護(hù)了一個(gè)RequestCache,用于緩存HttpServletRequest

11 . org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter

針對(duì)ServletRequest進(jìn)行了一次包裝,使得request具有更加豐富的API

12 . org.springframework.security.web.authentication.AnonymousAuthenticationFilter

當(dāng)SecurityContextHolder中認(rèn)證信息為空,則會(huì)創(chuàng)建一個(gè)匿名用戶存入到SecurityContextHolder中。

spring security為了兼容未登錄的訪問(wèn),也走了一套認(rèn)證流程,只不過(guò)是一個(gè)匿名的身份。

13 . org.springframework.security.web.session.SessionManagementFilter

SecurityContextRepository限制同一用戶開(kāi)啟多個(gè)會(huì)話的數(shù)量

14 . org.springframework.security.web.access.ExceptionTranslationFilter

異常轉(zhuǎn)換過(guò)濾器位于整個(gè)springSecurityFilterChain的后方,用來(lái)轉(zhuǎn)換整個(gè)鏈路中出現(xiàn)的異常

15 . org.springframework.security.web.access.intercept.FilterSecurityInterceptor

獲取所配置資源訪問(wèn)的授權(quán)信息,根據(jù)SecurityContextHolder中存儲(chǔ)的用戶信息來(lái)決定其是否有權(quán)限。

那么,是不是spring security一共就這么多過(guò)濾器呢?答案是否定的!隨著spring-security.xml配置的添加,還
會(huì)出現(xiàn)新的過(guò)濾器。

那么,是不是spring security每次都會(huì)加載這些過(guò)濾器呢?答案也是否定的!隨著spring-security.xml配置的修
改,有些過(guò)濾器可能會(huì)被去掉。

spring security 過(guò)濾器鏈加載原理

public class DelegatingFilterProxy extends GenericFilterBean {
@Nullable
private String contextAttribute;
@Nullable
private WebApplicationContext webApplicationContext;
@Nullable
private String targetBeanName;
private boolean targetFilterLifecycle;
@Nullable
private volatile Filter delegate;//注:這個(gè)過(guò)濾器才是真正加載的過(guò)濾器
private final Object delegateMonitor;
//注:doFilter才是過(guò)濾器的入口,直接從這看!
public void doFilter(ServletRequest request, ServletResponse response, FilterChain
filterChain) throws ServletException, IOException {
Filter delegateToUse = this.delegate;
if (delegateToUse == null) {
synchronized(this.delegateMonitor) {
delegateToUse = this.delegate;
if (delegateToUse == null) {
WebApplicationContext wac = this.findWebApplicationContext();
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: no
ContextLoaderListener or DispatcherServlet registered?");
}
//第一步:doFilter中最重要的一步,初始化上面私有過(guò)濾器屬性delegate
delegateToUse = this.initDelegate(wac);
}
this.delegate = delegateToUse;
}
}
//第三步:執(zhí)行FilterChainProxy過(guò)濾器
this.invokeDelegate(delegateToUse, request, response, filterChain);
}
//第二步:直接看最終加載的過(guò)濾器到底是誰(shuí)
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
//debug得知targetBeanName為:springSecurityFilterChain
String targetBeanName = this.getTargetBeanName();
Assert.state(targetBeanName != null, "No target bean name set");
//debug得知delegate對(duì)象為:FilterChainProxy
Filter delegate = (Filter)wac.getBean(targetBeanName, Filter.class);
if (this.isTargetFilterLifecycle()) {
delegate.init(this.getFilterConfig());
}
return delegate;
}
protected void invokeDelegate(Filter delegate, ServletRequest request, ServletResponse
response, FilterChain filterChain) throws ServletException, IOException {
delegate.doFilter(request, response, filterChain);
}
}

第二步debug結(jié)果如下:

Spring Security常用過(guò)濾器實(shí)例解析

Spring Security常用過(guò)濾器實(shí)例解析

由此可知, DelegatingFilterProxy通過(guò)springSecurityFilterChain這個(gè)名稱,得到了一個(gè)FilterChainProxy過(guò)濾器,
最終在第三步執(zhí)行了這個(gè)過(guò)濾器。

FilterChainProxy

public class FilterChainProxy extends GenericFilterBean {
private static final Log logger = LogFactory.getLog(FilterChainProxy.class);
private static final String FILTER_APPLIED =
FilterChainProxy.class.getName().concat(".APPLIED");
private List<SecurityFilterChain> filterChains;
private FilterChainProxy.FilterChainValidator filterChainValidator;
private HttpFirewall firewall;
//咿???可以通過(guò)一個(gè)叫SecurityFilterChain的對(duì)象實(shí)例化出一個(gè)FilterChainProxy對(duì)象
//這FilterChainProxy又是何方神圣?會(huì)不會(huì)是真正的過(guò)濾器鏈對(duì)象呢?先留著這個(gè)疑問(wèn)!
public FilterChainProxy(SecurityFilterChain chain) {
this(Arrays.asList(chain));
}
//又是SecurityFilterChain這家伙!嫌疑更大了!
public FilterChainProxy(List<SecurityFilterChain> filterChains) {
this.filterChainValidator = new FilterChainProxy.NullFilterChainValidator();
this.firewall = new StrictHttpFirewall();
this.filterChains = filterChains;
}
//注:直接從doFilter看
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean clearContext = 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 {
//第一步:具體操作調(diào)用下面的doFilterInternal方法了
this.doFilterInternal(request, response, chain);
}
}
private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain
chain) throws IOException, ServletException {
FirewalledRequest fwRequest =
this.firewall.getFirewalledRequest((HttpServletRequest)request);
HttpServletResponse fwResponse =
this.firewall.getFirewalledResponse((HttpServletResponse)response);
//第二步:封裝要執(zhí)行的過(guò)濾器鏈,那么多過(guò)濾器就在這里被封裝進(jìn)去了!
List<Filter> filters = this.getFilters((HttpServletRequest)fwRequest);
if (filters != null && filters.size() != 0) {
FilterChainProxy.VirtualFilterChain vfc = new
FilterChainProxy.VirtualFilterChain(fwRequest, chain, filters);
//第四步:加載過(guò)濾器鏈
vfc.doFilter(fwRequest, fwResponse);
} else {
if (logger.isDebugEnabled()) {
logger.debug(UrlUtils.buildRequestUrl(fwRequest) + (filters == null ? " has no
matching filters" : " has an empty filter list"));
}
fwRequest.reset();
chain.doFilter(fwRequest, fwResponse);
}
}
private List<Filter> getFilters(HttpServletRequest request) {
Iterator var2 = this.filterChains.iterator();
//第三步:封裝過(guò)濾器鏈到SecurityFilterChain中!
SecurityFilterChain chain;
do {
if (!var2.hasNext()) {
return null;
}
chain = (SecurityFilterChain)var2.next();
} while(!chain.matches(request));
return chain.getFilters();
}
}

Spring Security常用過(guò)濾器實(shí)例解析

SecurityFilterChain

最后看SecurityFilterChain,這是個(gè)接口,實(shí)現(xiàn)類也只有一個(gè),這才是web.xml中配置的過(guò)濾器鏈對(duì)象!

public interface SecurityFilterChain {
  boolean matches(HttpServletRequest request);
  List<Filter> getFilters();
}
public final class DefaultSecurityFilterChain implements SecurityFilterChain {
  private static final Log logger = LogFactory.getLog(DefaultSecurityFilterChain.class);
  private final RequestMatcher requestMatcher;
  private final List<Filter> filters;

  public DefaultSecurityFilterChain(RequestMatcher requestMatcher, Filter... filters) {
    this(requestMatcher, Arrays.asList(filters));
  }

  public DefaultSecurityFilterChain(RequestMatcher requestMatcher, List<Filter> filters) {
    logger.info("Creating filter chain: " + requestMatcher + ", " + filters);
    this.requestMatcher = requestMatcher;
    this.filters = new ArrayList<>(filters);
  }

  public RequestMatcher getRequestMatcher() {
    return requestMatcher;
  }

  public List<Filter> getFilters() {
    return filters;
  }

  public boolean matches(HttpServletRequest request) {
    return requestMatcher.matches(request);
  }

  @Override
  public String toString() {
    return "[ " + requestMatcher + ", " + filters + "]";
  }
}

Spring Security常用過(guò)濾器實(shí)例解析

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI