《shiro源码分析【整合spring】》(二)——Shiro过
二、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对象。可以在任何地方进行获取。
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;
}
这是配置的值,其会将请求的路径和等号前面的路径进行匹配。
mark至此,整个获取过滤器并执行的过程就结束了,接下来就是过滤器的具体执行了。
我们看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这两个方法进行实现即可。