二、Shiro過濾器
由于我們的分析只是基于web項(xiàng)目的竭宰,由配置文件我們可以知道空郊,在web項(xiàng)目中,shiro的入口是一個(gè)Filter類切揭。至于filter的初始化狞甚,在第一部分已經(jīng)介紹,接下來我們直接來看該過濾器是如何工作的廓旬。
由于集成spring的哼审,這個(gè)filter的具體實(shí)現(xiàn)類是:org.apache.shiro.spring.web.ShiroFilterFactoryBean.SpringShiroFilter
。這是一個(gè)內(nèi)部類嗤谚。這個(gè)類繼承自:org.apache.shiro.web.servlet.AbstractShiroFilter
,整個(gè)過濾器的核心處理方法都是在這個(gè)類實(shí)現(xiàn)的怔蚌,而SpringShiroFilter
只是做了一些初始化的工作巩步,具體可以看源碼:
private static final class SpringShiroFilter extends AbstractShiroFilter {
//構(gòu)造
protected SpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
super();
if (webSecurityManager == null) {
throw new IllegalArgumentException("WebSecurityManager property cannot be null.");
}
//設(shè)置SecurityManager
setSecurityManager(webSecurityManager);
//設(shè)置FilterChainResolver
if (resolver != null) {
setFilterChainResolver(resolver);
}
}
}
我們都知道一個(gè)過濾器的核心就是doFilter方法,SpringShiroFilter
這個(gè)類的doFilter方法的實(shí)現(xiàn)是由其父類:org.apache.shiro.web.servlet.OncePerRequestFilter
實(shí)現(xiàn)的桦踊。下面來看看這個(gè)doFilter方法的具體實(shí)現(xiàn)椅野。
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
//判斷當(dāng)前過濾器是否已經(jīng)執(zhí)行,如果已經(jīng)執(zhí)行則不進(jìn)行任何操作
if ( request.getAttribute(alreadyFilteredAttributeName) != null ) {
//日志
log.trace("Filter '{}' already executed. Proceeding without invoking this filter.", getName());
filterChain.doFilter(request, response);
} else //noinspection deprecation
if (/* added in 1.2: */ !isEnabled(request, response) ||
/* retain backwards compatibility: */ shouldNotFilter(request) ) {
log.debug("Filter '{}' is not enabled for the current request. Proceeding without invoking this filter.",
getName());
filterChain.doFilter(request, response);
} else {
// 在這里啟動(dòng)過濾器
log.trace("Filter '{}' not yet executed. Executing now.", getName());
// 注意:這里將當(dāng)前的過濾器名字進(jìn)行存儲(chǔ)
request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
try {
doFilterInternal(request, response, filterChain);
} finally {
// Once the request has finished, we're done and we don't
// need to mark as 'already filtered' any more.
request.removeAttribute(alreadyFilteredAttributeName);
}
}
}
由上面可以看到真正對(duì)請(qǐng)求進(jìn)行過處理的方法時(shí)doFilterInternal
這個(gè)方法籍胯。我們直接貼源碼竟闪。
protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, final FilterChain chain)
throws ServletException, IOException {
Throwable t = null;
try {
final ServletRequest request = prepareServletRequest(servletRequest, servletResponse, chain);
final ServletResponse response = prepareServletResponse(request, servletResponse, chain);
//這里其實(shí)就是初始化一個(gè)全局的subject對(duì)象≌壤牵可以在任何地方進(jìn)行獲取炼蛤。
final Subject subject = createSubject(request, response);
//這一步是主要的處理,有興趣的可以繼續(xù)跟蹤下代碼蝶涩,這里其實(shí)就是執(zhí)行回調(diào)里面的方法理朋。
subject.execute(new Callable() {
public Object call() throws Exception {
//看名字就知道這里不重要啦,哈哈绿聘!
updateSessionLastAccessTime(request, response);
//這個(gè)是關(guān)鍵
executeChain(request, response, chain);
return null;
}
});
} catch (ExecutionException ex) {
t = ex.getCause();
} catch (Throwable throwable) {
t = throwable;
}
if (t != null) {
if (t instanceof ServletException) {
throw (ServletException) t;
}
if (t instanceof IOException) {
throw (IOException) t;
}
//otherwise it's not one of the two exceptions expected by the filter method signature - wrap it in one:
String msg = "Filtered request failed.";
throw new ServletException(msg, t);
}
}
上面的代碼中嗽上,關(guān)鍵的就是的一個(gè)方法是executeChain
protected void executeChain(ServletRequest request, ServletResponse response, FilterChain origChain)
throws IOException, ServletException {
FilterChain chain = getExecutionChain(request, response, origChain);
chain.doFilter(request, response);
}
protected FilterChain getExecutionChain(ServletRequest request, ServletResponse response, FilterChain origChain) {
FilterChain chain = origChain;
//獲取解析器,如果為空就返回原始的過濾器
FilterChainResolver resolver = getFilterChainResolver();
if (resolver == null) {
log.debug("No FilterChainResolver configured. Returning original FilterChain.");
return origChain;
}
//從解析器中獲取過濾器熄攘。
FilterChain resolved = resolver.getChain(request, response, origChain);
if (resolved != null) {
log.trace("Resolved a configured FilterChain for the current request.");
chain = resolved;
} else {
log.trace("No FilterChain configured for the current request. Using the default.");
}
return chain;
}
//該方法在類:org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver#getChain 中
public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
//獲取過濾器鏈的管理器
FilterChainManager filterChainManager = getFilterChainManager();
if (!filterChainManager.hasChains()) {
return null;
}
//獲取當(dāng)前請(qǐng)求的相對(duì)路徑
String requestURI = getPathWithinApplication(request);
//the 'chain names' in this implementation are actually path patterns defined by the user. We just use them
//as the chain name for the FilterChainManager's requirements
//這個(gè)循環(huán)就是一個(gè)匹配的過程將當(dāng)前路徑與配置的路徑進(jìn)行比較兽愤,根據(jù)配置轉(zhuǎn)發(fā)到想應(yīng)的過濾器。
for (String pathPattern : filterChainManager.getChainNames()) {
// If the path does match, then pass on to the subclass implementation for specific checks:
if (pathMatches(pathPattern, requestURI)) {
if (log.isTraceEnabled()) {
log.trace("Matched path pattern [" + pathPattern + "] for requestURI [" + requestURI + "]. " +
"Utilizing corresponding filter chain...");
}
//這里好像看起來返回的是一個(gè)代理的過濾器挪圾!到底是不是浅萧?
return filterChainManager.proxy(originalChain, pathPattern);
}
}
return null;
}
這是配置的值,其會(huì)將請(qǐng)求的路徑和等號(hào)前面的路徑進(jìn)行匹配哲思。
至此惯殊,整個(gè)獲取過濾器并執(zhí)行的過程就結(jié)束了,接下來就是過濾器的具體執(zhí)行了也殖。
我們看return filterChainManager.proxy(originalChain, pathPattern);
這句話土思,他返回的是一個(gè)代理過濾器务热。可以從這里一步步跟蹤得到己儒,他真實(shí)返回對(duì)象是:org.apache.shiro.web.servlet.ProxiedFilterChain
崎岂。我們來看看他的doFilter方法:
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if (this.filters == null || this.filters.size() == this.index) {
//we've reached the end of the wrapped chain, so invoke the original one:
if (log.isTraceEnabled()) {
log.trace("Invoking original filter chain.");
}
this.orig.doFilter(request, response);
} else {
if (log.isTraceEnabled()) {
log.trace("Invoking wrapped filter at index [" + this.index + "]");
}
this.filters.get(this.index++).doFilter(request, response, this);
}
}
filters是一個(gè)集合,每執(zhí)行完一個(gè)過濾器闪湾,索引就往后走一位冲甘,如果當(dāng)前過濾器執(zhí)行不通過,可以進(jìn)行執(zhí)行下一個(gè)過濾器途样,而this.filters.get(this.index++).doFilter(request, response, this);
其實(shí)執(zhí)行的還是org.apache.shiro.web.servlet.OncePerRequestFilter
中的doFilter
這個(gè)方法江醇,周而復(fù)始,知道驗(yàn)證成功何暇,獲取全部失敗陶夜。
從上圖可以看到,shiro給我們提供了很多默認(rèn)的過濾器裆站,我們平時(shí)用到的大部分都是繼承自org.apache.shiro.web.filter.AccessControlFilter
条辟。既然是一個(gè)過濾器,那么他最重要的當(dāng)然是doFilter這個(gè)方法啦宏胯,跟蹤下發(fā)現(xiàn)羽嫡,doFilter這個(gè)方法在:org.apache.shiro.web.servlet.OncePerRequestFilter
這個(gè)方法的源碼,在前面已經(jīng)貼出肩袍。
有點(diǎn)不同的是杭棵,這次,我們傳入的過濾器是org.apache.shiro.web.servlet.AdviceFilter
這個(gè)類的子類實(shí)現(xiàn)氛赐,因此執(zhí)行的會(huì)是這個(gè)類的doFilterInternal方法颜屠。
public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
Exception exception = null;
try {
//前置處理
boolean continueChain = preHandle(request, response);
if (log.isTraceEnabled()) {
log.trace("Invoked preHandle method. Continuing chain?: [" + continueChain + "]");
}
if (continueChain) {
executeChain(request, response, chain);
}
//后置處理
postHandle(request, response);
if (log.isTraceEnabled()) {
log.trace("Successfully invoked postHandle method");
}
} catch (Exception e) {
exception = e;
} finally {
cleanup(request, response, exception);
}
}
這個(gè)其實(shí)很簡(jiǎn)單,就干了一件事鹰祸,稍微封裝了一下這個(gè)過濾器的doFilter方法甫窟。其中boolean continueChain = preHandle(request, response);
這句話是決定執(zhí)行不執(zhí)行這個(gè)filter的,但是當(dāng)前類只是簡(jiǎn)單的返回了一個(gè)true蛙婴。這個(gè)類粗井,好像沒有什么有意義的代碼。哈哈街图!這里我想大家可以猜到浇衬,這里的主要代碼都是在子類進(jìn)一步進(jìn)行實(shí)現(xiàn)的。由于我們是基于web應(yīng)用的額餐济,所以主要就看看org.apache.shiro.web.filter.PathMatchingFilter
:
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
if (this.appliedPaths == null || this.appliedPaths.isEmpty()) {
if (log.isTraceEnabled()) {
log.trace("appliedPaths property is null or empty. This Filter will passthrough immediately.");
}
return true;
}
for (String path : this.appliedPaths.keySet()) {
// If the path does match, then pass on to the subclass implementation for specific checks
//(first match 'wins'):
if (pathsMatch(path, request)) {
log.trace("Current requestURI matches pattern '{}'. Determining filter chain execution...", path);
Object config = this.appliedPaths.get(path);
return isFilterChainContinued(request, response, path, config);
}
}
//no path matched, allow the request to go through:
return true;
}
private boolean isFilterChainContinued(ServletRequest request, ServletResponse response,
String path, Object pathConfig) throws Exception {
if (isEnabled(request, response, path, pathConfig)) { //isEnabled check added in 1.2
if (log.isTraceEnabled()) {
log.trace("Filter '{}' is enabled for the current request under path '{}' with config [{}]. " +
"Delegating to subclass implementation for 'onPreHandle' check.",
new Object[]{getName(), path, pathConfig});
}
//The filter is enabled for this specific request, so delegate to subclass implementations
//so they can decide if the request should continue through the chain or not:
//這個(gè)是關(guān)鍵方法耘擂。但是當(dāng)前類只返回了一個(gè)true,不用想肯定要看子類了絮姆!
return onPreHandle(request, response, pathConfig);
}
if (log.isTraceEnabled()) {
log.trace("Filter '{}' is disabled for the current request under path '{}' with config [{}]. " +
"The next element in the FilterChain will be called immediately.",
new Object[]{getName(), path, pathConfig});
}
//This filter is disabled for this specific request,
//return 'true' immediately to indicate that the filter will not process the request
//and let the request/response to continue through the filter chain:
return true;
}
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
return true;
}
接下來我們可以到org.apache.shiro.web.filter.AccessControlFilter
看看onPreHandle
這個(gè)方法的實(shí)現(xiàn):
public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
//執(zhí)行isAccessAllowed和onAccessDenied這兩個(gè)方法醉冤;
//由于||的特性秩霍,所以當(dāng)isAccessAllowed返回false時(shí)才會(huì)執(zhí)行onAccessDenied
return isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response, mappedValue);
}
//交由子類進(jìn)行實(shí)現(xiàn)
protected abstract boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception;
protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
return onAccessDenied(request, response);
}
//交由子類進(jìn)行實(shí)現(xiàn)
protected abstract boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception;
至此,shiro的過濾器就差不多這樣了蚁阳,我們?cè)趯?shí)際開發(fā)當(dāng)中铃绒,可以繼承自AccessControlFilter這個(gè)方法,對(duì)isAccessAllowed螺捐,onAccessDenied這兩個(gè)方法進(jìn)行實(shí)現(xiàn)即可颠悬。