Apache Shiro 使用手冊(五)Shiro 配置說明

Apache Shiro的配置主要分爲四部分:
  • 對象和屬性的定義與配置
  • URL的過濾器配置
  • 靜態用戶配置
  • 靜態角色配置
其中,由於用戶、角色一般由後臺進行操作的動態數據,因此Shiro配置一般僅包含前兩項的配置。

Apache Shiro的大多數組件是基於POJO的,因此我們可以使用POJO兼容的任何配置機制進行配置,例如:Java代碼、Sping XML、YAML、JSON、ini文件等等。下面,以Spring XML的配置方式爲例,並且對其中的一些配置參數進行一些簡單說明。

Shiro對象的配置:
主要是對Shiro各個組件的實現進行定義配置,主要組件在前文已做過簡單介紹,這裏不再一一說明。
Xml代碼  
    <bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">  
            <property name="cacheManager" ref="cacheManager"/>  
            <property name="sessionMode" value="native"/>  
            <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->  
            <property name="realm" ref="myRealm"/>  
            <property name="sessionManager" ref="sessionManager"/>   
    </bean>  

Shiro過濾器的配置
Shiro主要是通過URL過濾來進行安全管理,這裏的配置便是指定具體授權規則定義。
Xml代碼
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <property name="securityManager" ref="securityManager"/>  
        <property name="loginUrl" value="/login.jsp"/>  
        <property name="successUrl" value="/home.jsp"/>  
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/> -->  
        <property name="filterChainDefinitions">  
            <value>  
                # some example chain definitions:  
                /admin/** = authc, roles[admin]  
                /docs/** = authc, perms[document:read]  
                /** = authc  
                # more URL-to-FilterChain definitions here  
            </value>  
        </property>  
    </bean>  

URL過濾器配置說明:
Shiro可以通過配置文件實現基於URL的授權驗證。FilterChain定義格式:
URL_Ant_Path_Expression = Path_Specific_Filter_Chain
每個URL配置,表示匹配該URL的應用程序請求將由對應的過濾器進行驗證。
例如:
[urls]
/index.html = anon
/user/create = anon
/user/** = authc
/admin/** = authc, roles[administrator]
/rest/** = authc, rest
/remoting/rpc/** = authc, perms["remote:invoke"]

URL表達式說明
1、URL目錄是基於HttpServletRequest.getContextPath()此目錄設置
2、URL可使用通配符,**代表任意子目錄
3、Shiro驗證URL時,URL匹配成功便不再繼續匹配查找。所以要注意配置文件中的URL順序,尤其在使用通配符時。

Filter Chain定義說明
1、一個URL可以配置多個Filter,使用逗號分隔
2、當設置多個過濾器時,全部驗證通過,才視爲通過
3、部分過濾器可指定參數,如perms,roles

Shiro內置的FilterChain
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
perms org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
port org.apache.shiro.web.filter.authz.PortFilter
rest org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
roles org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
ssl org.apache.shiro.web.filter.authz.SslFilter
user org.apache.shiro.web.filter.authc.UserFilter
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章