這篇文章主要介紹了spring-boot是如何集成shiro的authentication流程的。
從shiro-spring-boot-web-starter說起
shiro-spring-boot-web-starter是shiro在web環境下快速集成至spring-boot的配置包。其本身引入了shiro的必要模塊。並在Configuration中以@Bean的形式聲明了Shiro各組件,交由spring容器統一管理。先看META-INF定義了配置類:
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration,\
org.apache.shiro.spring.config.web.autoconfigure.ShiroWebFilterConfiguration
可以看到主要有兩個配置:ShiroWebAutoConfiguration和ShiroWebFilterConfiguration。
- ShiroWebAutoConfiguration
ShiroWebAutoConfiguration聲明了Shiro需要的各個對象,在需要shiro框架進行處理的地方,可以方便注入,從而到達應用shiro特性的目的。同理,我們也可以根據需要替換上述部分Bean,讓Shiro的流程更負責自己的業務需求。
/**
* @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();
}
}
- ShiroWebFilterConfiguration
以往spring項目的權限控制大多也是通過過濾器或是攔截器實現的,即請求在到達控制器之前,先經過過濾器或攔截器的處理,如果校驗成功,再將數據發送至控制器。Shiro也是利用同樣的道理。
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。
ShiroFilterFactoryBean
ShiroFilterFactoryBean同時實現了FactoryBean和BeanPostProcessor。說明他同時有創建Bean和Bean的后置處理兩種能力。簡單看一下源代碼:
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的實例,大致過程分成三步:
- 通過
createFilterChainManager()創建FilterChainManager對象:- 創建
FilterChainManager - 加載Shiro默認的Filter
- 加載用戶添加的Filter
- 根據URL和Filter的映射關系,創建過濾器鏈
- 創建
- 創建
FilterChainResolver對象,封裝FilterChainManager - 創建
ShiroFilter對象,傳入SecurityManager和FilterChainReslover
SpringShiroFilter
SpringShiroFilter就是我們通過容器添加的Filter對象。Shiro通過添加該過濾器實現了往集成Spring框架集成的目的。
其實SpringShiroFilter只是單純的集成了AbstractShiroFilter,在構造函數中增加了設置SecurityManager和FilterChainResolver的過程。所有的邏輯在AbstractShiroFilter中已經定義好了。先從UML圖中了解下整個類的繼承關系:

其中從上到下看:
- Filter
Filter是Serlvet包提供的。由Servlet規范定義Filter基本的行為。 - ServletContextSupport
提供了操作ServletContext的能力 - AbstractFilter
初步實現了Filter,定義了init的過程(分成setFilterConfig和onFilterConfigSet兩部分),提供了設置和獲取配置的方法。 - Nameable
增加了命名的能力 - NameableFilter
為Filter增加命名能力 - OncePerRequestFilter
主要定義了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
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()主要流程:
- 先封裝了請求和響應
- 獲取請求代表的
Subject對象 - 更新session最后訪問的時間(托管給WEB容器的session不需要shiro管理訪問時間)
- 執行攔截器鏈
executeChain:- 獲取攔截器鏈: 如果FilterChainResolver解析到請求的URL是shiro攔截器攔截的URL,則產生代理的FilterChain,讓shiro的攔截器集成進攔截器;否則使用原始的攔截器鏈
- 攔截器鏈開始工作
FilterChainResolver和FilterChainManager的工作
之前簡單介紹過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的流程。
從FormAuthenticatingFilter了解Shiro的authentication過程
一樣先看Filter的繼承結構:

OncePerRequestFilter父級的結構已經在前文介紹過。現在關注點放在它的子類上。
- AdviceFilter:
主要實現了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);
}
}
- PathMatchingFilter:根據url是否匹配的邏輯實現
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;
}
- AccessControlFilter:主要重寫了
onPreHandle方法,增加了isAccessAllowed和onAccessDenied方法。可以在該方法中實現訪問控制的邏輯。
public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
return isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response, mappedValue);
}
- AuthenticationFilter:實現了
isAccessAllowed方法,通過subject.isAuthenticated()決定是否允許訪問。
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
Subject subject = getSubject(request, response);
return subject.isAuthenticated();
}
- AuthenticatingFilter:除了主要的
isAccessAllowed和cleanup方法之外,還實現了executeLogin方法,主要是從請求中獲取登錄的用戶名密碼,通過shiro進行登錄驗證 - FormAuthenticationFilter:最后具體看一下
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。
