Shiro學習筆記(二)Spring + Shiro整合

Shiro官網提供了兩種Integrations方式,一個是和Spring整合,一個是和Guice整合,這兩個框架的特點都是有IOC,而且Guice本身就是一個輕量級的IOC框架。

我現在做的項目都使用Spring Boot,但Spring Boot的話並不推薦使用XML文件配置,所以需要根據官網提供的XML配置來轉換成Java類配置,但由於都是基於Spring的框架,原理是一樣的,所以只需要理解Shiro配置部分使用的類的作用就好。以下就是我對官網提供的XML配置方法的理解。

 


 

Spring啓動Shiro的最簡單的方法:

<!-- Define the realm you want to use to connect to your back-end security datasource: -->
<bean id="myRealm" class="...">
    ...
</bean>

<bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">
    <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
    <property name="realm" ref="myRealm"/>
</bean>

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- For simplest integration, so that all SecurityUtils.* methods work in all cases, -->
<!-- make the securityManager bean a static singleton.  DO NOT do this in web         -->
<!-- applications - see the 'Web Applications' section below instead.                 -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
    <property name="arguments" ref="securityManager"/>
</bean>

從上面看,最快啓動Shiro的方法,只需要自定義一個Realm,即,Shiro框架中與數據庫的安全信息數據進行交互的模塊。將自定義的Realm交由Spring管理,然後注入到默認安全管理器中,默認安全管理器也交由Spring管理。

org.apache.shiro.spring.LifecycleBeanPostProcessor這個類它自動調用Shiro對象上的init()和/或destroy()方法,實現org.apache.shiro.util.Initializable或org.apache.shiro.util.Destroyable接口。

爲了實現最簡單的集成,因此所有SecurityUtils.*方法在所有情況下都工作,因此需要將securityManager bean設置爲靜態單例。換句話說,org.springframework.beans.factory.config.MethodInvokingFactoryBean是一個Spring的方法調用的bean工廠,它的值是靜態或實例方法調用的結果,而Shiro需要在SecurityUtils中調用setSecurityManager()將安全管理器設置進去,參數依賴於前面聲明的默認安全管理器。

 


 

web.xml配置:

<!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

...

<!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->
<!-- requests.  Usually this filter mapping is defined first (before all others) to -->
<!-- ensure that Shiro works in subsequent filters in the filter chain:             -->
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

這裏就是普通的Java Web項目中的web.xml文件配置,Spring過濾配置依賴於bean名爲shiroFilter的bean,過濾的url設置爲全局,並且也依賴於shiroFilter。

 

applicationContext.xml配置

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <!-- override these for application-specific URLs if you like:
    <property name="loginUrl" value="/login.jsp"/>
    <property name="successUrl" value="/home.jsp"/>
    <property name="unauthorizedUrl" value="/unauthorized.jsp"/> -->
    <!-- The 'filters' property is not necessary since any declared javax.servlet.Filter bean  -->
    <!-- defined will be automatically acquired and available via its beanName in chain        -->
    <!-- definitions, but you can perform instance overrides or name aliases here if you like: -->
    <!-- <property name="filters">
        <util:map>
            <entry key="anAlias" value-ref="someFilter"/>
        </util:map>
    </property> -->
    <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>

<!-- Define any javax.servlet.Filter beans you want anywhere in this application context.   -->
<!-- They will automatically be acquired by the 'shiroFilter' bean above and made available -->
<!-- to the 'filterChainDefinitions' property.  Or you can manually/explicitly add them     -->
<!-- to the shiroFilter's 'filters' Map if desired. See its JavaDoc for more details.       -->
<bean id="someFilter" class="..."/>
<bean id="anotherFilter" class="..."> ... </bean>
...

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
    <property name="realm" ref="myRealm"/>
    <!-- By default the servlet container sessions will be used.  Uncomment this line
         to use shiro's native sessions (see the JavaDoc for more): -->
    <!-- <property name="sessionMode" value="native"/> -->
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- Define the Shiro Realm implementation you want to use to connect to your back-end -->
<!-- security datasource: -->
<bean id="myRealm" class="...">
    ...
</bean>

這裏聲明的shiroFilter就是web.xml裏依賴的那個,它是Shiro的一個過濾器類的bean工廠,用來配置各種url過濾及權限設置。類中定義有的變量是securityManager、filters、filterChainDefinitionMap、loginUrl、successUrl、unauthorizedUrl、instance,相對重要的變量就是securityManager與filterChainDefinitionMap了。securityManager的作用不用多說,來說說filterChainDefinitionMap和loginUrl這類特殊url的作用。

filterChainDefinitionMap的作用,就是用來存放各種url以及url對應的攔截方式,Map的key爲要攔截的url,value爲Shiro的攔截方式。而從bean工廠類ShiroFilterFactoryBean的源碼可知,該類在實例化的時候就同時把filterChainDefinitionMap和filters也實例化了,filters使用的是HashMap(),而filterChainDefinitionMap使用的是LinkedHashMap()。

filterChainDefinitionMap使用LinkedHashMap()的原因,正如後面的那個註釋所說,攔截url配置的順序非常重要,正因如此選擇了具有順序且線程同步的LinkedHashMap()。對於特殊url其實Shiro已經提供了一些完整的過濾器配置,而我們不需要去自定義,提供對應的url,Shiro會自動。loginUrl:登錄頁面url,該值將通過AccessControlFilter.setLoginUrl(String)方法傳遞給每個Filter;successUrl:登錄成功後跳轉的url,該值將通過AuthenticationFilter.setSuccessUrl(String)方法傳遞給每個Filter。unauthorizedUrl:無權限跳轉的url,該值將通過AuthorizationFilter.setUnauthorizedUrl(String)方法傳遞給每個Filter。

 


 

啓用Shiro註解:

若要啓用Shiro的註解進行安全檢查的話,就需要使用Spring AOP來掃描帶註解的類,並根據需要執行安全邏輯。而啓用註解只需要在applicationContext.xml中添加下面的配置:

<!-- Enable Shiro Annotations for Spring-configured beans.  Only run after -->
<!-- the lifecycleBeanProcessor has run: -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>

這裏創建的DefaultAdvisorAutoProxyCreator依賴於之前創建的lifecycleBeanPostProcessor這個bean,會在它創建完後纔開始創建,是一個通用的創建AOP代理,它不包含用於處理任何特定方面(如池方面)的特殊代碼。創建AuthorizationAttributeSourceAdvisor設置的安全管理器依舊ref之前創建的安全管理器。

 


 

至此,Shiro的配置基本已完成,可以總結一下需要用到的類。首先從最底層開始:

  1. (自定義)Realm,相關包路徑org.apache.shiro.realm

  2. ShiroFilterFactoryBean,類路徑org.apache.shiro.spring.web.ShiroFilterFactoryBean

  3. Filters,相關包路徑org.apache.shiro.web.filter

  4. DefaultWebSecurityManager,類路徑org.apache.shiro.web.mgt.DefaultWebSecurityManager

  5. AuthorizationAttributeSourceAdvisor,類路徑org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor

也就是說,不光是Spring,Spring Boot也可以針對將上面這些類交由Spring管理,並完善其中的配置,即可將Shiro整合並能正常使用。

 

Shiro官網 - Integrations-Spring

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章