二、Shiro過濾器
由于我們的分析只是基于web項目的,由配置文件我們可以知道,在web項目中,shiro的入口是一個Filter類。至于filter的初始化,在第一部分已經介紹,接下來我們直接來看該過濾器是如何工作的。
由于集成spring的,這個filter的具體實現類是:org.apache.shiro.spring.web.ShiroFilterFactoryBean.SpringShiroFilter
。這是一個內部類。這個類繼承自:org.apache.shiro.web.servlet.AbstractShiroFilter
,整個過濾器的核心處理方法都是在這個類實現的,而SpringShiroFilter
只是做了一些初始化的工作,具體可以看源碼:
private static final class SpringShiroFilter extends AbstractShiroFilter {
//構造
protected SpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
super();
if (webSecurityManager == null) {
throw new IllegalArgumentException("WebSecurityManager property cannot be null.");
}
//設置SecurityManager
setSecurityManager(webSecurityManager);
//設置FilterChainResolver
if (resolver != null) {
setFilterChainResolver(resolver);
}
}
}
我們都知道一個過濾器的核心就是doFilter方法,SpringShiroFilter
這個類的doFilter方法的實現是由其父類:org.apache.shiro.web.servlet.OncePerRequestFilter
實現的。下面來看看這個doFilter方法的具體實現。
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
//判斷當前過濾器是否已經執行,如果已經執行則不進行任何操作
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 {
// 在這里啟動過濾器
log.trace("Filter '{}' not yet executed. Executing now.", getName());
// 注意:這里將當前的過濾器名字進行存儲
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);
}
}
}
由上面可以看到真正對請求進行過處理的方法時doFilterInternal
這個方法。我們直接貼源碼。
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);
//這里其實就是初始化一個全局的subject對象??梢栽谌魏蔚胤竭M行獲取。
final Subject subject = createSubject(request, response);
//這一步是主要的處理,有興趣的可以繼續跟蹤下代碼,這里其實就是執行回調里面的方法。
subject.execute(new Callable() {
public Object call() throws Exception {
//看名字就知道這里不重要啦,哈哈!
updateSessionLastAccessTime(request, response);
//這個是關鍵
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);
}
}
上面的代碼中,關鍵的就是的一個方法是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;
}
//獲取當前請求的相對路徑
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
//這個循環就是一個匹配的過程將當前路徑與配置的路徑進行比較,根據配置轉發到想應的過濾器。
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...");
}
//這里好像看起來返回的是一個代理的過濾器!到底是不是?
return filterChainManager.proxy(originalChain, pathPattern);
}
}
return null;
}
這是配置的值,其會將請求的路徑和等號前面的路徑進行匹配。
至此,整個獲取過濾器并執行的過程就結束了,接下來就是過濾器的具體執行了。
我們看return filterChainManager.proxy(originalChain, pathPattern);
這句話,他返回的是一個代理過濾器??梢詮倪@里一步步跟蹤得到,他真實返回對象是: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是一個集合,每執行完一個過濾器,索引就往后走一位,如果當前過濾器執行不通過,可以進行執行下一個過濾器,而this.filters.get(this.index++).doFilter(request, response, this);
其實執行的還是org.apache.shiro.web.servlet.OncePerRequestFilter
中的doFilter
這個方法,周而復始,知道驗證成功,獲取全部失敗。
從上圖可以看到,shiro給我們提供了很多默認的過濾器,我們平時用到的大部分都是繼承自org.apache.shiro.web.filter.AccessControlFilter
。既然是一個過濾器,那么他最重要的當然是doFilter這個方法啦,跟蹤下發現,doFilter這個方法在:org.apache.shiro.web.servlet.OncePerRequestFilter
這個方法的源碼,在前面已經貼出。
有點不同的是,這次,我們傳入的過濾器是org.apache.shiro.web.servlet.AdviceFilter
這個類的子類實現,因此執行的會是這個類的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);
}
}
這個其實很簡單,就干了一件事,稍微封裝了一下這個過濾器的doFilter方法。其中boolean continueChain = preHandle(request, response);
這句話是決定執行不執行這個filter的,但是當前類只是簡單的返回了一個true。這個類,好像沒有什么有意義的代碼。哈哈!這里我想大家可以猜到,這里的主要代碼都是在子類進一步進行實現的。由于我們是基于web應用的額,所以主要就看看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:
//這個是關鍵方法。但是當前類只返回了一個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
這個方法的實現:
public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
//執行isAccessAllowed和onAccessDenied這兩個方法;
//由于||的特性,所以當isAccessAllowed返回false時才會執行onAccessDenied
return isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response, mappedValue);
}
//交由子類進行實現
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);
}
//交由子類進行實現
protected abstract boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception;
至此,shiro的過濾器就差不多這樣了,我們在實際開發當中,可以繼承自AccessControlFilter這個方法,對isAccessAllowed,onAccessDenied這兩個方法進行實現即可。