標籤:blog http io ar os 使用 sp for strong
先不談Spring,首先試著用最簡易的方式將Shiro整合到web應用。 即使用一些Servlet ContextListener、Filter、ini這些簡單的配置完成與web應用的整合。
web.xml:
<listener> <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class></listener><context-param> <param-name>shiroEnvironmentClass</param-name> <param-value>org.apache.shiro.web.env.IniWebEnvironment</param-value></context-param><context-param> <param-name>shiroConfigLocations</param-name> <param-value>classpath:shiro_web.ini</param-value></context-param>
上面的配置中我註冊了一個Listener——org.apache.shiro.web.env.EnvironmentLoaderListener。
該類的意義主要是為了實現ServletContextListener,將WebEnvironment隨著ServletContext事件進行建立和銷毀。
對WebEnvironment的處理邏輯全部在其父類——EnvironmentLoader中。
WebEnvironment的類別關係圖:
如果想擷取WebEnvironment則可以試試以下方法:
WebUtils.getRequiredWebEnvironment(servletContext);
上面的配置中用到了兩個參數(事實上EnvironmentLoader也只有這兩個參數)。
- shiroEnvironmentClass
- shiroConfigLocations
shiroEnvironmentClass用於指定使用的WebEnvironment實作類別,預設值為org.apache.shiro.web.env.IniWebEnvironment。
IniWebEnvironment根據設定的.ini設定檔的路徑建立ini執行個體,如果無法獲得.ini設定檔則拋出ConfigurationException。
當然,如果有需要(比如換個配置格式、解析方法什麼的...),我們也可以自己實現一個WebEnvirontment,並通過shiroEnvironmentClass屬性來進行註冊。
而shiroConfigLocations則是指定.ini設定檔的路徑的參數。
如果沒有進行手動指定,他會嘗試在以下兩個路徑中尋找:
public static final String DEFAULT_WEB_INI_RESOURCE_PATH = "/WEB-INF/shiro.ini";public static final String DEFAULT_INI_RESOURCE_PATH = "classpath:shiro.ini";
順便記錄,IniWebEnvironment尋找.ini配置時使用ResourceUtils,見:
private Ini convertPathToIni(String path, boolean required) { //TODO - this logic is ugly - it‘d be ideal if we had a Resource API to polymorphically encaspulate this behavior Ini ini = null; if (StringUtils.hasText(path)) { InputStream is = null; //SHIRO-178: Check for servlet context resource and not only resource paths: if (!ResourceUtils.hasResourcePrefix(path)) { is = getServletContextResourceStream(path); } else { try { is = ResourceUtils.getInputStreamForPath(path); } catch (IOException e) { if (required) { throw new ConfigurationException(e); } else { if (log.isDebugEnabled()) { log.debug("Unable to load optional path ‘" + path + "‘.", e); } } } } if (is != null) { ini = new Ini(); ini.load(is); } else { if (required) { throw new ConfigurationException("Unable to load resource path ‘" + path + "‘"); } } } return ini;}
該方法首先調用ResourceUtils.hasResourcePrefix(path)檢查路徑首碼是否符合以下三種之一:
public static final String CLASSPATH_PREFIX = "classpath:";public static final String URL_PREFIX = "url:";public static final String FILE_PREFIX = "file:";
如果不符合這三種首碼則在Servlet Context進行尋找。
如果符合三種首碼之一,則調用ResourceUtils.getInputStreamForPath(path),根據path及其不同的首碼以不同的方式擷取輸入資料流。
對於classpath,調用ClassUtils.getResourceAsStream(path);,通過ClassLoader執行個體調用getResourceAsStream(name);
對於url,則是返回url.openStream();
對於file,返回new FileInputStream(path);
繼續配置web.xml,這次添加一個Filter:
<filter> <filter-name>ShiroFilter</filter-name> <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class> </filter><filter-mapping> <filter-name>ShiroFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping>
這是基於當前的WebEnvironment執行個體配置的Filter,即單獨存在沒什麼意義。
ShiroFilter用WebEnvironment執行個體對所有被過濾的請求進行安全處理。
Shiro提供的一些Filter實現:
暫且不論AdviceFilter,我們使用的ShiroFilter在AbstractShiroFilter下。
其中IniShiroFilter從1.2開始已deprecated了,但這個東西用起來還是有點意思的,只不過沒什麼意義。
IniShiroFilter不需要同時配置EnvironmentLoaderListener,也就是說這裡面沒有WebEnvironment對象,他本身就是一個簡易的Environment。
有意思的地方就是這點,他可以把.ini中的配置直接寫到web.xml,比如這樣:
<filter> <filter-name>ShiroFilter</filter-name> <filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class> <init-param> <param-name>config</param-name> <param-value> [urls] /main/logout = logout /main/loginPage = anon /** = user [main] user.loginUrl = /main/login authc.successUrl = /main/welcome myRealm=pac.king.common.security.realm.MainRealm securityManager.realms=$myRealm </param-value> </init-param></filter><filter-mapping> <filter-name>ShiroFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher></filter-mapping>
有意思,但沒什麼意義。
Shiro也建議使用者們不要這樣配置,對此他們給出了幾個理由:
- 安全配置可能會經常變化,而我們不想總是修改web.xml。
- 安全配置可能會越來越龐大,這會影響web.xml的可讀性。
- 我們盡量保證安全配置不會散落在各個地方。
無論如何,這取決於使用者和項目。
另外說說web應用相關的ini配置。
之前幾篇中用過[main]、[users]、[roles]等片段,在web應用中我們可以試試[urls]。
[urls]也是Shiro的一大賣點(文檔提供人說根本沒見過其他web framework也能做到這點)。
就是為每個URL配置專有的filter chain!!
[urls]的格式如下:
URL_Ant_Path_Expression = Path_Specific_Filter_Chain[optional_config]
左側使用Ant風格的運算式描述URL;
右側則是用逗號分隔的過濾器鏈;
最後的optional_config則是一些附加屬性,比如描述對使用者資源有刪除操作的許可權perms["user:delete"]。
配置[urls],官網上的例子:
[urls]/index.html = anon/user/create = anon/user/** = authc/admin/** = authc, roles[administrator]/rest/** = authc, rest/remoting/rpc/** = authc, perms["remote:invoke"]
URL是相對路徑,即使部署的時候換了個網域名稱也沒有問題。
注意!URL配置的順序對filter chain是有影響的!他是FIRST MATCH WINS。
比如下面的例子中,第二行配置就不會生效。
/user/** = authc/user/list = anon
預設的Filter,比如anon,authc,users等等,他們是由哪些類來實現的?
| Filter Name |
Class |
| anon |
org.apache.shiro.web.filter.authc.AnonymousFilter |
| authc |
org.apache.shiro.web.filter.authc.FormAuthenticationFilter |
| authcBasic |
org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter |
| logout |
org.apache.shiro.web.filter.authc.LogoutFilter |
| noSessionCreation |
org.apache.shiro.web.filter.session.NoSessionCreationFilter |
| perms |
org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter |
| port |
org.apache.shiro.web.filter.authz.PortFilter |
| rest |
org.apache.shiro.web.filter.authz.HttpMethodPermissionFilterv |
| roles |
org.apache.shiro.web.filter.authz.RolesAuthorizationFilter |
| ssl |
org.apache.shiro.web.filter.authz.SslFilter |
| user |
org.apache.shiro.web.filter.authc.UserFilter |
應用啟動時,將預設Filter全部載入。
預設Filter的定義見enum類DefaultFilter。
pool of Filters則定義在DefaultFilterChainManager中,用LinkedHashMap維護。DefaultFilterChainManager在constructor中調用void addDefaultFilters(boolean init)將Filters放入Map中。
隨著應用做得越來越大,這些URL會變得越來越難以管理。
當然,我們也可以把這些URL放在資料庫裡管理,但總是有個別的URL需要特殊配置Filter。
就以我現在工作中的應用為例,我們將大多數URL放到資料庫管理,並全部採用authc+perms過濾器,perms的options也是該URL。
即有該URL許可權的使用者可以訪問該URL。
但總有那麼些例外的、奇怪的東西,除了資料庫裡的URL,我又在.ini中寫了差不多30個URL,再配上各種各樣的Filter,當然還要注意順序的影響。
隨著開發、測試、生產環境的切換,這些filters也需要可以進行啟用/禁用。
我總不把filter能一個個刪掉再一個個寫回去...
見OncePerRequestFilter有個field:
private boolean enabled = true;
而且所有的default filters都繼承了OncePerRequestFilter!!
於是我可以直接在ini檔案中直接進行啟用/禁用,比如這樣:
user.enabled=false
當然,我們也可以試著自訂一個Filter(比如根據判斷具體的請求或者路徑,動態將所有filter啟用/禁用),並在[main]註冊。
另外,上面的類別關係圖中AccessControlFilter有一個field為loginUrl,其預設值為:
public static final String DEFAULT_LOGIN_URL = "/login.jsp";
我們經常使用的filter中的authc(FormAuthenticationFilter)中存在以下屬性:
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 String usernameParam = DEFAULT_USERNAME_PARAM;private String passwordParam = DEFAULT_PASSWORD_PARAM;private String rememberMeParam = DEFAULT_REMEMBER_ME_PARAM;
我們可以在表單中使用這些屬性,讓其進行認證+remember me。
當然,這些值也是可以改變的,比如:
[main]authc.loginUrl = /main/loginauthc.usernameParam = userNameauthc.passwordParam = pwdauthc.rememberMeParam = rememberCookie
說到remember me,其實現是有RememberMeManager提供,預設實現是基於Cookie的。
比如DefaultWebSecurityManager的constructor中將CookieRememberMeManager設為預設(field定義於其父類DefaultSecurityManager):
public DefaultWebSecurityManager() { super(); ((DefaultSubjectDAO) this.subjectDAO).setSessionStorageEvaluator(new DefaultWebSessionStorageEvaluator()); this.sessionMode = HTTP_SESSION_MODE; setSubjectFactory(new DefaultWebSubjectFactory()); setRememberMeManager(new CookieRememberMeManager()); setSessionManager(new ServletContainerSessionManager());}
看起來不錯,那我就一步步detect看看RememberMeManager是怎麼manage的。
使用者登入時我們調用Subject.login(token)以DelegaingSubject為例,第一步直接將驗證工作委託給securityManager。
工作中一步步進行委託,securityManager -> authenticator -> realm...
驗證通過後將AuthenticationInfo結果返回到securityManager,securityManager將結果傳遞給RememberMeManager,委託rememberMe的工作。
參考AbstractRememberMeManager中的method:
public void onSuccessfulLogin(Subject subject, AuthenticationToken token, AuthenticationInfo info) { //always clear any previous identity: forgetIdentity(subject); //now save the new identity: if (isRememberMe(token)) { rememberIdentity(subject, token, info); } else { if (log.isDebugEnabled()) { log.debug("AuthenticationToken did not indicate RememberMe is requested. " + "RememberMe functionality will not be executed for corresponding account."); } }}
第一步:先將Cookie移除,Shiro預設使用的Cookie是自己的SimpleCookie,調用其removeFrom方法將Cookie"移除"。
第二步:檢查token是否是RememberMeAuthenticationToken的執行個體並是否設定了rememberMe=true。
第三步:進行rememberMe的具體工作,這個工作由AbstractRememberMeManager的子類進行。
以CookieRememberMeManager為例:
protected void rememberSerializedIdentity(Subject subject, byte[] serialized) { if (!WebUtils.isHttp(subject)) { if (log.isDebugEnabled()) { String msg = "Subject argument is not an HTTP-aware instance. This is required to obtain a servlet " + "request and response in order to set the rememberMe cookie. Returning immediately and " + "ignoring rememberMe operation."; log.debug(msg); } return; } HttpServletRequest request = WebUtils.getHttpRequest(subject); HttpServletResponse response = WebUtils.getHttpResponse(subject); //base 64 encode it and store as a cookie: String base64 = Base64.encodeToString(serialized); Cookie template = getCookie(); //the class attribute is really a template for the outgoing cookies Cookie cookie = new SimpleCookie(template); cookie.setValue(base64); cookie.saveTo(request, response);}
代碼非常簡單,接著轉到SimpleCookie:
public void saveTo(HttpServletRequest request, HttpServletResponse response) { String name = getName(); String value = getValue(); String comment = getComment(); String domain = getDomain(); String path = calculatePath(request); int maxAge = getMaxAge(); int version = getVersion(); boolean secure = isSecure(); boolean httpOnly = isHttpOnly(); addCookieHeader(response, name, value, comment, domain, path, maxAge, version, secure, httpOnly);}private void addCookieHeader(HttpServletResponse response, String name, String value, String comment, String domain, String path, int maxAge, int version, boolean secure, boolean httpOnly) { String headerValue = buildHeaderValue(name, value, comment, domain, path, maxAge, version, secure, httpOnly); response.addHeader(COOKIE_HEADER_NAME, headerValue); if (log.isDebugEnabled()) { log.debug("Added HttpServletResponse Cookie [{}]", headerValue); }}
但畢竟很多人不喜歡cookie...我們也可以自己去實現RememberMeManager,並進行註冊(仍然是注入到securityManger):
rememberMeManager = com.my.impl.RememberMeManagersecurityManager.rememberMeManager = $rememberMeManager
我們使用的UsernamePasswordToken繼承的RememberMeAuthenticationToken提供rememberMe特性。
boolean isRememberMe();
比如我們可以Realm的驗證方法中這樣使用:
UsernamePasswordToken uToken = (UsernamePasswordToken)token;uToken.setRememberMe(true);
Shiro - web應用