這篇文章主要介紹了spring-boot是如何集成shiro的authentication流程的。java
shiro-spring-boot-web-starter是shiro在web環境下快速集成至spring-boot的配置包。其自己引入了shiro的必要模塊。並在Configuration中以@Bean的形式聲明瞭Shiro各組件,交由spring容器統一管理。先看META-INF定義了配置類:web
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \ org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration,\ org.apache.shiro.spring.config.web.autoconfigure.ShiroWebFilterConfiguration
能夠看到主要有兩個配置:ShiroWebAutoConfiguration和ShiroWebFilterConfiguration。spring
/** * @since 1.4.0 */ @Configuration @AutoConfigureBefore(ShiroAutoConfiguration.class) @ConditionalOnProperty(name = "shiro.web.enabled", matchIfMissing = true) public class ShiroWebAutoConfiguration extends AbstractShiroWebConfiguration { //聲明瞭認證時的策略,默認是AtLeastOneSuccessfulStrategy @Bean @ConditionalOnMissingBean @Override protected AuthenticationStrategy authenticationStrategy() { return super.authenticationStrategy(); } //聲明Authenticator對象,負責認證的過程 @Bean @ConditionalOnMissingBean @Override protected Authenticator authenticator() { return super.authenticator(); } //聲明Authorizer的對象,負責受權的過程 @Bean @ConditionalOnMissingBean @Override protected Authorizer authorizer() { return super.authorizer(); } //聲明Subject數據訪問對象,經過該對象能夠對Subject數據進行CRUD操做 @Bean @ConditionalOnMissingBean @Override protected SubjectDAO subjectDAO() { return super.subjectDAO(); } //聲明SessionStorageEvaluator對象,用來決定Session是否須要持久化 @Bean @ConditionalOnMissingBean @Override protected SessionStorageEvaluator sessionStorageEvaluator() { return super.sessionStorageEvaluator(); } //聲明SubjectFactory,用來建立Subject對象 @Bean @ConditionalOnMissingBean @Override protected SubjectFactory subjectFactory() { return super.subjectFactory(); } //聲明SessionFactory對象,用來建立Session @Bean @ConditionalOnMissingBean @Override protected SessionFactory sessionFactory() { return super.sessionFactory(); } //聲明Session數據訪問對象,提供對Session的CRUD操做 @Bean @ConditionalOnMissingBean @Override protected SessionDAO sessionDAO() { return super.sessionDAO(); } //聲明SessionManager對象,負責Session管理 @Bean @ConditionalOnMissingBean @Override protected SessionManager sessionManager() { return super.sessionManager(); } //聲明SecurityMananger,Shiro中最重要的組件,對象內封裝了各個其餘對象,用來處理不一樣的業務 @Bean @ConditionalOnMissingBean @Override protected SessionsSecurityManager securityManager(List<Realm> realms) { return createSecurityManager(); } //建立會話cookie時的模板,後期應用該模板的屬性到建立的cookie對象上 @Bean @ConditionalOnMissingBean(name = "sessionCookieTemplate") @Override protected Cookie sessionCookieTemplate() { return super.sessionCookieTemplate(); } //Remember Me Manager,管理RememerMe @Bean @ConditionalOnMissingBean @Override protected RememberMeManager rememberMeManager() { return super.rememberMeManager(); } //RememberMe模板 @Bean @ConditionalOnMissingBean(name = "rememberMeCookieTemplate") @Override protected Cookie rememberMeCookieTemplate() { return super.rememberMeCookieTemplate(); } //定義了Shiro的Filter和URL的映射關係 @Bean @ConditionalOnMissingBean @Override protected ShiroFilterChainDefinition shiroFilterChainDefinition() { return super.shiroFilterChainDefinition(); } }
package org.apache.shiro.spring.config.web.autoconfigure; import javax.servlet.DispatcherType; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.spring.web.config.AbstractShiroWebFilterConfiguration; import org.apache.shiro.web.servlet.AbstractShiroFilter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @since 1.4.0 */ @Configuration @ConditionalOnProperty(name = "shiro.web.enabled", matchIfMissing = true) public class ShiroWebFilterConfiguration extends AbstractShiroWebFilterConfiguration { //ShiroFilter的FactoryBean,用來建立ShiroFilter @Bean @ConditionalOnMissingBean @Override protected ShiroFilterFactoryBean shiroFilterFactoryBean() { return super.shiroFilterFactoryBean(); } //ShiroFilter的RegistrationBean,spring-boot捨棄了web.xml的配置,FilterRegistrationBean就成了添加filter的入口 @Bean(name = "filterShiroFilterRegistrationBean") @ConditionalOnMissingBean protected FilterRegistrationBean filterShiroFilterRegistrationBean() throws Exception { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ERROR); filterRegistrationBean.setFilter((AbstractShiroFilter) shiroFilterFactoryBean().getObject()); filterRegistrationBean.setOrder(1); return filterRegistrationBean; } }
FilterRegistrationBean
主要設置了要添加的Filter
是由ShiroFilterFactoryBean
所建立。所以,咱們重點關注ShiroFilterFactoryBean。apache
ShiroFilterFactoryBean
同時實現了FactoryBean
和BeanPostProcessor
。說明他同時有建立Bean和Bean的後置處理兩種能力。簡單看一下源代碼:cookie
package org.apache.shiro.spring.web; public class ShiroFilterFactoryBean implements FactoryBean, BeanPostProcessor { private static transient final Logger log = LoggerFactory.getLogger(ShiroFilterFactoryBean.class); private SecurityManager securityManager; //定義了攔截器name和Filter的映射關係 private Map<String, Filter> filters; //定義了攔截器URL和name的映射關係 private Map<String, String> filterChainDefinitionMap; //urlPathExpression_to_comma-delimited-filter-chain-definition private String loginUrl; private String successUrl; private String unauthorizedUrl; private AbstractShiroFilter instance; public ShiroFilterFactoryBean() { this.filters = new LinkedHashMap<String, Filter>(); this.filterChainDefinitionMap = new LinkedHashMap<String, String>(); //order matters! } public SecurityManager getSecurityManager() { return securityManager; } public void setSecurityManager(SecurityManager securityManager) { this.securityManager = securityManager; } public String getLoginUrl() { return loginUrl; } public void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } public String getSuccessUrl() { return successUrl; } public void setSuccessUrl(String successUrl) { this.successUrl = successUrl; } public String getUnauthorizedUrl() { return unauthorizedUrl; } public void setUnauthorizedUrl(String unauthorizedUrl) { this.unauthorizedUrl = unauthorizedUrl; } public Map<String, Filter> getFilters() { return filters; } public void setFilters(Map<String, Filter> filters) { this.filters = filters; } public Map<String, String> getFilterChainDefinitionMap() { return filterChainDefinitionMap; } public void setFilterChainDefinitionMap(Map<String, String> filterChainDefinitionMap) { this.filterChainDefinitionMap = filterChainDefinitionMap; } //提供了經過ini配置文件初始化Filter的能力 public void setFilterChainDefinitions(String definitions) { Ini ini = new Ini(); ini.load(definitions); //did they explicitly state a 'urls' section? Not necessary, but just in case: Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS); if (CollectionUtils.isEmpty(section)) { //no urls section. Since this _is_ a urls chain definition property, just assume the //default section contains only the definitions: section = ini.getSection(Ini.DEFAULT_SECTION_NAME); } setFilterChainDefinitionMap(section); } //FactoryBean獲取Bean的方法,這裏就是獲取對應Filter Bean public Object getObject() throws Exception { if (instance == null) { instance = createInstance(); } return instance; } //FactoryBean獲取生成的Bean的類型 public Class getObjectType() { return SpringShiroFilter.class; } //要生成的Bean是否須要是單例 public boolean isSingleton() { return true; } //建立FilterChainManager對象,該對象能夠將對應的url和filter組成過濾器鏈 protected FilterChainManager createFilterChainManager() { DefaultFilterChainManager manager = new DefaultFilterChainManager(); //Shiro自帶的Filter,不須要額外配置,能夠開箱即用,詳見DefualtFilter Map<String, Filter> defaultFilters = manager.getFilters(); for (Filter filter : defaultFilters.values()) { applyGlobalPropertiesIfNecessary(filter); } //獲取ShiroFactoryBean中自定義的Filters,添加至manager中 Map<String, Filter> filters = getFilters(); if (!CollectionUtils.isEmpty(filters)) { for (Map.Entry<String, Filter> entry : filters.entrySet()) { String name = entry.getKey(); Filter filter = entry.getValue(); applyGlobalPropertiesIfNecessary(filter); if (filter instanceof Nameable) { ((Nameable) filter).setName(name); } //'init' argument is false, since Spring-configured filters should be initialized //in Spring (i.e. 'init-method=blah') or implement InitializingBean: manager.addFilter(name, filter, false); } } //根據定義的url和filter映射關係,建立過濾器鏈 Map<String, String> chains = getFilterChainDefinitionMap(); if (!CollectionUtils.isEmpty(chains)) { for (Map.Entry<String, String> entry : chains.entrySet()) { String url = entry.getKey(); String chainDefinition = entry.getValue(); manager.createChain(url, chainDefinition); } } return manager; } //建立ShiroFilter的實例 protected AbstractShiroFilter createInstance() throws Exception { log.debug("Creating Shiro Filter instance."); SecurityManager securityManager = getSecurityManager(); if (securityManager == null) { String msg = "SecurityManager property must be set."; throw new BeanInitializationException(msg); } if (!(securityManager instanceof WebSecurityManager)) { String msg = "The security manager does not implement the WebSecurityManager interface."; throw new BeanInitializationException(msg); } FilterChainManager manager = createFilterChainManager(); //Expose the constructed FilterChainManager by first wrapping it in a // FilterChainResolver implementation. The AbstractShiroFilter implementations // do not know about FilterChainManagers - only resolvers: //建立FilterChainResolver對象,FilterChainResolver包裝了Manager,ShiroFilter不須要知道Manager對象 PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver(); chainResolver.setFilterChainManager(manager); //Now create a concrete ShiroFilter instance and apply the acquired SecurityManager and built //FilterChainResolver. It doesn't matter that the instance is an anonymous inner class //here - we're just using it because it is a concrete AbstractShiroFilter instance that accepts //injection of the SecurityManager and FilterChainResolver: //建立ShiroFilter對象 return new SpringShiroFilter((WebSecurityManager) securityManager, chainResolver); } private void applyLoginUrlIfNecessary(Filter filter) { String loginUrl = getLoginUrl(); if (StringUtils.hasText(loginUrl) && (filter instanceof AccessControlFilter)) { AccessControlFilter acFilter = (AccessControlFilter) filter; //only apply the login url if they haven't explicitly configured one already: String existingLoginUrl = acFilter.getLoginUrl(); if (AccessControlFilter.DEFAULT_LOGIN_URL.equals(existingLoginUrl)) { acFilter.setLoginUrl(loginUrl); } } } private void applySuccessUrlIfNecessary(Filter filter) { String successUrl = getSuccessUrl(); if (StringUtils.hasText(successUrl) && (filter instanceof AuthenticationFilter)) { AuthenticationFilter authcFilter = (AuthenticationFilter) filter; //only apply the successUrl if they haven't explicitly configured one already: String existingSuccessUrl = authcFilter.getSuccessUrl(); if (AuthenticationFilter.DEFAULT_SUCCESS_URL.equals(existingSuccessUrl)) { authcFilter.setSuccessUrl(successUrl); } } } private void applyUnauthorizedUrlIfNecessary(Filter filter) { String unauthorizedUrl = getUnauthorizedUrl(); if (StringUtils.hasText(unauthorizedUrl) && (filter instanceof AuthorizationFilter)) { AuthorizationFilter authzFilter = (AuthorizationFilter) filter; //only apply the unauthorizedUrl if they haven't explicitly configured one already: String existingUnauthorizedUrl = authzFilter.getUnauthorizedUrl(); if (existingUnauthorizedUrl == null) { authzFilter.setUnauthorizedUrl(unauthorizedUrl); } } } //配置全局屬性,只要是針對特定類型的Filter配置其所須要的URL屬性 private void applyGlobalPropertiesIfNecessary(Filter filter) { applyLoginUrlIfNecessary(filter); applySuccessUrlIfNecessary(filter); applyUnauthorizedUrlIfNecessary(filter); } //經過後置處理器的機制,直接Filter類型的bean,無需配置 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof Filter) { log.debug("Found filter chain candidate filter '{}'", beanName); Filter filter = (Filter) bean; applyGlobalPropertiesIfNecessary(filter); getFilters().put(beanName, filter); } else { log.trace("Ignoring non-Filter bean '{}'", beanName); } return bean; } /** * Does nothing - only exists to satisfy the BeanPostProcessor interface and immediately returns the * {@code bean} argument. */ public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } //SpringShiroFilter只是簡單的集成了AbstractShirlFilter,在構造函數中封裝了設置SecurityManager和Resolver的操做 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."); } setSecurityManager(webSecurityManager); if (resolver != null) { setFilterChainResolver(resolver); } } } }
最重要的步驟是在createInstance()
中,該方法主要用來建立ShiroFilter的實例,大體過程分紅三步:session
createFilterChainManager()
建立FilterChainManager
對象:
FilterChainManager
FilterChainResolver
對象,封裝FilterChainManager
ShiroFilter
對象,傳入SecurityManager
和FilterChainReslover
SpringShiroFilter
就是咱們經過容器添加的Filter對象。Shiro經過添加該過濾器實現了往集成Spring框架集成的目的。
其實SpringShiroFilter
只是單純的集成了AbstractShiroFilter
,在構造函數中增長了設置SecurityManager
和FilterChainResolver
的過程。全部的邏輯在AbstractShiroFilter
中已經定義好了。先從UML圖中瞭解下整個類的繼承關係:app
其中從上到下看:框架
setFilterConfig
和onFilterConfigSet
兩部分),提供了設置和獲取配置的方法。doFilter
的過程,並在該過程當中限制了一次請求該Filter只處理一次。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 { //調用Filter處理,並添加已處理屬性 // Do invoke this filter... 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); } } }
AbstractShiroFilter
已經在Filter的處理過程當中添加了Shiro的驗證。package org.apache.shiro.web.servlet; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.apache.shiro.subject.ExecutionException; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.mgt.FilterChainResolver; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.mgt.WebSecurityManager; import org.apache.shiro.web.subject.WebSubject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.concurrent.Callable; public abstract class AbstractShiroFilter extends OncePerRequestFilter { private static final Logger log = LoggerFactory.getLogger(AbstractShiroFilter.class); private static final String STATIC_INIT_PARAM_NAME = "staticSecurityManagerEnabled"; // Reference to the security manager used by this filter private WebSecurityManager securityManager; // Used to determine which chain should handle an incoming request/response private FilterChainResolver filterChainResolver; /** * Whether or not to bind the constructed SecurityManager instance to static memory (via * SecurityUtils.setSecurityManager). This was added to support https://issues.apache.org/jira/browse/SHIRO-287 * @since 1.2 */ private boolean staticSecurityManagerEnabled; protected AbstractShiroFilter() { this.staticSecurityManagerEnabled = false; } public WebSecurityManager getSecurityManager() { return securityManager; } public void setSecurityManager(WebSecurityManager sm) { this.securityManager = sm; } public FilterChainResolver getFilterChainResolver() { return filterChainResolver; } public void setFilterChainResolver(FilterChainResolver filterChainResolver) { this.filterChainResolver = filterChainResolver; } public boolean isStaticSecurityManagerEnabled() { return staticSecurityManagerEnabled; } public void setStaticSecurityManagerEnabled(boolean staticSecurityManagerEnabled) { this.staticSecurityManagerEnabled = staticSecurityManagerEnabled; } //重寫了AbstractFilter中的空實現,主要設置額外的配置 protected final void onFilterConfigSet() throws Exception { //added in 1.2 for SHIRO-287: applyStaticSecurityManagerEnabledConfig(); init(); ensureSecurityManager(); //added in 1.2 for SHIRO-287: if (isStaticSecurityManagerEnabled()) { SecurityUtils.setSecurityManager(getSecurityManager()); } } private void applyStaticSecurityManagerEnabledConfig() { String value = getInitParam(STATIC_INIT_PARAM_NAME); if (value != null) { Boolean b = Boolean.valueOf(value); if (b != null) { setStaticSecurityManagerEnabled(b); } } } public void init() throws Exception { } private void ensureSecurityManager() { WebSecurityManager securityManager = getSecurityManager(); if (securityManager == null) { log.info("No SecurityManager configured. Creating default."); securityManager = createDefaultSecurityManager(); setSecurityManager(securityManager); } } protected WebSecurityManager createDefaultSecurityManager() { return new DefaultWebSecurityManager(); } protected boolean isHttpSessions() { return getSecurityManager().isHttpSessionMode(); } protected ServletRequest wrapServletRequest(HttpServletRequest orig) { return new ShiroHttpServletRequest(orig, getServletContext(), isHttpSessions()); } @SuppressWarnings({"UnusedDeclaration"}) protected ServletRequest prepareServletRequest(ServletRequest request, ServletResponse response, FilterChain chain) { ServletRequest toUse = request; if (request instanceof HttpServletRequest) { HttpServletRequest http = (HttpServletRequest) request; toUse = wrapServletRequest(http); } return toUse; } protected ServletResponse wrapServletResponse(HttpServletResponse orig, ShiroHttpServletRequest request) { return new ShiroHttpServletResponse(orig, getServletContext(), request); } @SuppressWarnings({"UnusedDeclaration"}) protected ServletResponse prepareServletResponse(ServletRequest request, ServletResponse response, FilterChain chain) { ServletResponse toUse = response; if (!isHttpSessions() && (request instanceof ShiroHttpServletRequest) && (response instanceof HttpServletResponse)) { //the ShiroHttpServletResponse exists to support URL rewriting for session ids. This is only needed if //using Shiro sessions (i.e. not simple HttpSession based sessions): toUse = wrapServletResponse((HttpServletResponse) response, (ShiroHttpServletRequest) request); } return toUse; } protected WebSubject createSubject(ServletRequest request, ServletResponse response) { return new WebSubject.Builder(getSecurityManager(), request, response).buildWebSubject(); } //對Session生命週期未交給Web容器管理的狀況,由Shiro本身維護 @SuppressWarnings({"UnusedDeclaration"}) protected void updateSessionLastAccessTime(ServletRequest request, ServletResponse response) { if (!isHttpSessions()) { //'native' sessions Subject subject = SecurityUtils.getSubject(); //Subject should never _ever_ be null, but just in case: if (subject != null) { Session session = subject.getSession(false); if (session != null) { try { session.touch(); } catch (Throwable t) { log.error("session.touch() method invocation has failed. Unable to update" + "the corresponding session's last access time based on the incoming request.", t); } } } } } //重寫OncePerRequestFilter的空實現,定義了Filter處理邏輯 protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, final FilterChain chain) throws ServletException, IOException { Throwable t = null; try { //封裝ServletRequest和ServletResponse final ServletRequest request = prepareServletRequest(servletRequest, servletResponse, chain); final ServletResponse response = prepareServletResponse(request, servletResponse, chain); //建立Subject對象 final Subject subject = createSubject(request, response); //noinspection unchecked subject.execute(new Callable() { public Object call() throws Exception { //更新Session訪問時間 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); } } //獲取待執行的過濾器鏈 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) { //若是該請求URI是須要Shiro攔截的,則由shiro建立代理的過濾器鏈, //在執行原始的過濾器前,插入Shiro過濾器的執行過程 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; } //執行攔截器鏈 protected void executeChain(ServletRequest request, ServletResponse response, FilterChain origChain) throws IOException, ServletException { //獲取攔截器鏈 FilterChain chain = getExecutionChain(request, response, origChain); //攔截器鏈處理攔截工做 chain.doFilter(request, response); } }
其中比較重要的有兩個:onFilterConfigSet()
和doFilterInternal()
。
onFilterConfigset()
在AbstractFilter
中是空實現,這裏重寫了該方法,主要是添加一些額外配置。
doFilterInternal()
主要流程:ide
Subject
對象executeChain
:
以前簡單介紹過FilterChainResolver封裝了FilterChainManger對象,如今再來看下FilterChainResovler的代碼:函數
public class PathMatchingFilterChainResolver implements FilterChainResolver { private static transient final Logger log = LoggerFactory.getLogger(PathMatchingFilterChainResolver.class); //封裝了FilterChainManager private FilterChainManager filterChainManager; //負責比較URL private PatternMatcher pathMatcher; public PathMatchingFilterChainResolver() { this.pathMatcher = new AntPathMatcher(); this.filterChainManager = new DefaultFilterChainManager(); } public PathMatchingFilterChainResolver(FilterConfig filterConfig) { this.pathMatcher = new AntPathMatcher(); this.filterChainManager = new DefaultFilterChainManager(filterConfig); } public PatternMatcher getPathMatcher() { return pathMatcher; } public void setPathMatcher(PatternMatcher pathMatcher) { this.pathMatcher = pathMatcher; } public FilterChainManager getFilterChainManager() { return filterChainManager; } @SuppressWarnings({"UnusedDeclaration"}) public void setFilterChainManager(FilterChainManager filterChainManager) { this.filterChainManager = filterChainManager; } //獲取攔截器鏈 public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) { FilterChainManager filterChainManager = getFilterChainManager(); if (!filterChainManager.hasChains()) { return null; } //獲取URL String requestURI = getPathWithinApplication(request); //匹配URL for (String pathPattern : filterChainManager.getChainNames()) { //若是匹配,則由filterChainManager建立代理過的Filter Chain 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; } protected boolean pathMatches(String pattern, String path) { PatternMatcher pathMatcher = getPathMatcher(); return pathMatcher.matches(pattern, path); } protected String getPathWithinApplication(ServletRequest request) { return WebUtils.getPathWithinApplication(WebUtils.toHttp(request)); } }
這個類的代碼相對簡單,大概過程是根據FilterChainManager
配置的URI和Filter的映射關係,比較請求是否須要通過Shiro的Filter,若是須要則交給了FilterChainManager
對象建立代理過的FilterChain,從而加入了Shiro的處理流程。能夠看到主要的內容都是由FilterChainManager
完成。所以咱們再來看FilterChainManager
類的proxy
方法:
public FilterChain proxy(FilterChain original, String chainName) { //NamedFilterList對象能夠簡單理解爲一個命名了Filter的list,是以前解析filter時,建立的 NamedFilterList configured = getChain(chainName); if (configured == null) { String msg = "There is no configured chain under the name/key [" + chainName + "]."; throw new IllegalArgumentException(msg); } //建立代理 return configured.proxy(original); }
NamedFilterList
建立代理的過程其實就是建立ProxiedFilterChain
對象。
public class ProxiedFilterChain implements FilterChain { //TODO - complete JavaDoc private static final Logger log = LoggerFactory.getLogger(ProxiedFilterChain.class); private FilterChain orig; private List<Filter> filters; private int index = 0; public ProxiedFilterChain(FilterChain orig, List<Filter> filters) { if (orig == null) { throw new NullPointerException("original FilterChain cannot be null."); } //封裝了原始filterChain對象和shiro的filter對象 this.orig = orig; this.filters = filters; this.index = 0; } //實現了filterChain的doFilter方法 public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { //若是不含有shiro的filter,或是已經遍歷完了shiro的filter,則調用原始的fiter chain的方法 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 + "]"); } //調用shiro的filter this.filters.get(this.index++).doFilter(request, response, this); } } }
源碼讀到這裏已經大體瞭解到shiro是如何集成至spring-boot的。接下來再以一個Shiro的Filter爲例,具體瞭解下authentication的流程。
同樣先看Filter
的繼承結構:
OncePerRequestFilter
父級的結構已經在前文介紹過。如今關注點放在它的子類上。
doFilterInternal
方法,將filter的過程再切成preHandle
,executeChain
,postHandle
和cleanup
四個階段。有點相似spring中的攔截器。在方法前,方法後作了攔截。並根據返回的結果決定是否繼續再filterChain中往下走:public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { Exception exception = null; try { //前置處理,根據返回結構決定是否繼續走以後的filter boolean continueChain = preHandle(request, response); if (log.isTraceEnabled()) { log.trace("Invoked preHandle method. Continuing chain?: [" + continueChain + "]"); } //繼續調用以後的filter 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); } }
preHandle
方法。並提供onPreHandle
方法讓子類能夠修改preHandle方法返回的值。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; } //匹配請求URL,決定是否須要通過shiro的filter for (String path : this.appliedPaths.keySet()) { 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; } @SuppressWarnings({"JavaDoc"}) 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}); } //添加onPreHandle方法 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; } //默認返回true,子類能夠重寫該方法實現本身的控制邏輯 protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { return true; }
onPreHandle
方法,增長了isAccessAllowed
和onAccessDenied
方法。能夠在該方法中實現訪問控制的邏輯。public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { return isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response, mappedValue); }
isAccessAllowed
方法,經過subject.isAuthenticated()
決定是否容許訪問。protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { Subject subject = getSubject(request, response); return subject.isAuthenticated(); }
isAccessAllowed
和cleanup
方法以外,還實現了executeLogin
方法,主要是從請求中獲取登陸的用戶名密碼,經過shiro進行登陸驗證FormAuthenticationFilter
。public class FormAuthenticationFilter extends AuthenticatingFilter { //TODO - complete JavaDoc public static final String DEFAULT_ERROR_KEY_ATTRIBUTE_NAME = "shiroLoginFailure"; public static final String DEFAULT_USERNAME_PARAM = "username"; public static final String DEFAULT_PASSWORD_PARAM = "password"; public static final String DEFAULT_REMEMBER_ME_PARAM = "rememberMe"; private static final Logger log = LoggerFactory.getLogger(FormAuthenticationFilter.class); private String usernameParam = DEFAULT_USERNAME_PARAM; private String passwordParam = DEFAULT_PASSWORD_PARAM; private String rememberMeParam = DEFAULT_REMEMBER_ME_PARAM; private String failureKeyAttribute = DEFAULT_ERROR_KEY_ATTRIBUTE_NAME; public FormAuthenticationFilter() { setLoginUrl(DEFAULT_LOGIN_URL); } @Override public void setLoginUrl(String loginUrl) { String previous = getLoginUrl(); if (previous != null) { this.appliedPaths.remove(previous); } super.setLoginUrl(loginUrl); if (log.isTraceEnabled()) { log.trace("Adding login url to applied paths."); } this.appliedPaths.put(getLoginUrl(), null); } public String getUsernameParam() { return usernameParam; } public void setUsernameParam(String usernameParam) { this.usernameParam = usernameParam; } public String getPasswordParam() { return passwordParam; } public void setPasswordParam(String passwordParam) { this.passwordParam = passwordParam; } public String getRememberMeParam() { return rememberMeParam; } public void setRememberMeParam(String rememberMeParam) { this.rememberMeParam = rememberMeParam; } public String getFailureKeyAttribute() { return failureKeyAttribute; } public void setFailureKeyAttribute(String failureKeyAttribute) { this.failureKeyAttribute = failureKeyAttribute; } // protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { //若是isAccessAllowed校驗失敗,則判斷是不是登陸請求 if (isLoginRequest(request, response)) { //若是是表單提交的登陸請求,則執行登陸, if (isLoginSubmission(request, response)) { if (log.isTraceEnabled()) { log.trace("Login submission detected. Attempting to execute login."); } //登陸 return executeLogin(request, response); } else { if (log.isTraceEnabled()) { log.trace("Login page view."); } //allow them to see the login page ;) return true; } } else { if (log.isTraceEnabled()) { log.trace("Attempting to access a path which requires authentication. Forwarding to the " + "Authentication url [" + getLoginUrl() + "]"); } saveRequestAndRedirectToLogin(request, response); return false; } } @SuppressWarnings({"UnusedDeclaration"}) protected boolean isLoginSubmission(ServletRequest request, ServletResponse response) { return (request instanceof HttpServletRequest) && WebUtils.toHttp(request).getMethod().equalsIgnoreCase(POST_METHOD); } protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) { String username = getUsername(request); String password = getPassword(request); return createToken(username, password, request, response); } protected boolean isRememberMe(ServletRequest request) { return WebUtils.isTrue(request, getRememberMeParam()); } //定義了一些重定向動做 protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { issueSuccessRedirect(request, response); //we handled the success redirect directly, prevent the chain from continuing: return false; } protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { if (log.isDebugEnabled()) { log.debug( "Authentication exception", e ); } setFailureAttribute(request, e); //login failed, let request continue back to the login page: return true; } protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) { String className = ae.getClass().getName(); request.setAttribute(getFailureKeyAttribute(), className); } protected String getUsername(ServletRequest request) { return WebUtils.getCleanParam(request, getUsernameParam()); } protected String getPassword(ServletRequest request) { return WebUtils.getCleanParam(request, getPasswordParam()); } }
shiro經過FilterRegistrationBean添加了ShiroFilter。ShiroFilter在針對須要登陸驗證的請求,將原始的fiterChain進行代理,從而集成了shiro權限驗證的filter。