Java學(xué)習(xí)

          java,spring,structs,hibernate,jsf,ireport,jfreechart,jasperreport,tomcat,jboss -----本博客已經(jīng)搬家了,新的地址是 http://www.javaly.cn 如果有對(duì)文章有任何疑問(wèn)或者有任何不懂的地方,歡迎到www.javaly.cn (Java樂(lè)園)指出,我會(huì)盡力幫助解決。一起進(jìn)步

           

          Acegi Security -- Spring下最優(yōu)秀的安全系統(tǒng)(zhuan)

          一 Acegi安全系統(tǒng)介紹

              Author: cac 差沙

              Acegi是Spring Framework 下最成熟的安全系統(tǒng),它提供了強(qiáng)大靈活的企業(yè)級(jí)安全服務(wù),如完善的認(rèn)證和授權(quán)機(jī)制,Http資源訪問(wèn)控制,Method 調(diào)用訪問(wèn)控制,Access Control List (ACL) 基于對(duì)象實(shí)例的訪問(wèn)控制,Yale Central Authentication Service (CAS) 耶魯單點(diǎn)登陸,X509 認(rèn)證,當(dāng)前所有流行容器的認(rèn)證適配器,Channel Security頻道安全管理等功能。

          1.1 網(wǎng)站資源

          官方網(wǎng)站      http://acegisecurity.sourceforge.net
          論壇            http://forum.springframework.org/forumdisplay.php?f=33
          Jira              http://opensource.atlassian.com/projects/spring/browse/SEC

          1.2 多方面的安全控制粒度

          1. URL 資源訪問(wèn)控制
             http://apps:8080/index.htm -> for public
             http://apps:8080/user.htm -> for authorized user
          2. 方法調(diào)用訪問(wèn)控制
            public void getData() -> all user
            public void modifyData() -> supervisor only
          3. 對(duì)象實(shí)例保護(hù)
            order.getValue() < $100 -> all user
            order.getValue() > $100 -> supervisor only

          1.3 非入侵式安全架構(gòu)

          1. 基于Servlet Filter和Spring aop,  使商業(yè)邏輯和安全邏輯分開(kāi),結(jié)構(gòu)更清晰
          2. 使用Spring 來(lái)代理對(duì)象,能方便地保護(hù)方法調(diào)用

          1.4 其它安全架構(gòu)

              Acegi只是安全框架之一,其實(shí)還存在其它優(yōu)秀的安全框架可供選擇:

           

          二 Acegi安全系統(tǒng)的配置

                Acegi 的配置看起來(lái)非常復(fù)雜,但事實(shí)上在實(shí)際項(xiàng)目的安全應(yīng)用中我們并不需要那么多功能,清楚的了解Acegi配置中各項(xiàng)的功能,有助于我們靈活的運(yùn)用Acegi于實(shí)踐中。

          2.1 在Web.xml中的配置

          1)  FilterToBeanProxy
          Acegi通過(guò)實(shí)現(xiàn)了Filter接口的 FilterToBeanProxy提供一種特殊的使用Servlet Filter的方式,它委托Spring中的Bean -- FilterChainProxy來(lái)完成過(guò)濾功能,這好處是簡(jiǎn)化了web.xml的配置,并且充分利用了Spring IOC的優(yōu)勢(shì)。FilterChainProxy包含了處理認(rèn)證過(guò)程的filter列表,每個(gè)filter都有各自的功能。

              <filter>
                  <filter-name>Acegi Filter Chain Proxy</filter-name>
                  <filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
                  <init-param>
                      <param-name>targetClass</param-name>
                      <param-value>org.acegisecurity.util.FilterChainProxy</param-value>
                  </init-param>
              </filter>

          2) filter-mapping
          <filter-mapping>限定了FilterToBeanProxy的URL匹配模式,只有*.do和*.jsp和/j_acegi_security_check 的請(qǐng)求才會(huì)受到權(quán)限控制,對(duì)javascript,css等不限制。

             <filter-mapping>
                <filter-name>Acegi Filter Chain Proxy</filter-name>
                <url-pattern>*.do</url-pattern>
              </filter-mapping>
             
              <filter-mapping>
                <filter-name>Acegi Filter Chain Proxy</filter-name>
                <url-pattern>*.jsp</url-pattern>
              </filter-mapping>
             
              <filter-mapping>
                <filter-name>Acegi Filter Chain Proxy</filter-name>
                <url-pattern>/j_acegi_security_check</url-pattern>
          </filter-mapping>

          3) HttpSessionEventPublisher
          <listener>的 HttpSessionEventPublisher用于發(fā)布HttpSessionApplicationEvents和 HttpSessionDestroyedEvent事件給spring的applicationcontext。

              <listener>
                  <listener-class>org.acegisecurity.ui.session.HttpSessionEventPublisher</listener-class>
              </listener>


          2.2 在applicationContext-acegi-security.xml中

          2.2.1 FILTER CHAIN

            FilterChainProxy會(huì)按順序來(lái)調(diào)用這些filter,使這些filter能享用Spring ioc的功能, CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON定義了url比較前先轉(zhuǎn)為小寫(xiě), PATTERN_TYPE_APACHE_ANT定義了使用Apache ant的匹配模式

              <bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
                  <property name="filterInvocationDefinitionSource">
                      <value>
                          CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
                          PATTERN_TYPE_APACHE_ANT
                         /**=httpSessionContextIntegrationFilter,authenticationProcessingFilter,
          basicProcessingFilter,rememberMeProcessingFilter,anonymousProcessingFilter,
          exceptionTranslationFilter,filterInvocationInterceptor
                      </value>
                  </property>
              </bean>

          2.2.2 基礎(chǔ)認(rèn)證

          1) authenticationManager
          起到認(rèn)證管理的作用,它將驗(yàn)證的功能委托給多個(gè) Provider,并通過(guò)遍歷Providers, 以保證獲取不同來(lái)源的身份認(rèn)證,若某個(gè)Provider能成功確認(rèn)當(dāng)前用戶的身份,authenticate()方法會(huì)返回一個(gè)完整的包含用戶授權(quán)信息的 Authentication對(duì)象,否則會(huì)拋出一個(gè)AuthenticationException。
          Acegi提供了不同的AuthenticationProvider的實(shí)現(xiàn),如:
                  DaoAuthenticationProvider 從數(shù)據(jù)庫(kù)中讀取用戶信息驗(yàn)證身份
                  AnonymousAuthenticationProvider 匿名用戶身份認(rèn)證
                  RememberMeAuthenticationProvider 已存cookie中的用戶信息身份認(rèn)證
                  AuthByAdapterProvider 使用容器的適配器驗(yàn)證身份
                  CasAuthenticationProvider 根據(jù)Yale中心認(rèn)證服務(wù)驗(yàn)證身份, 用于實(shí)現(xiàn)單點(diǎn)登陸
                  JaasAuthenticationProvider 從JASS登陸配置中獲取用戶信息驗(yàn)證身份
                  RemoteAuthenticationProvider 根據(jù)遠(yuǎn)程服務(wù)驗(yàn)證用戶身份
                  RunAsImplAuthenticationProvider 對(duì)身份已被管理器替換的用戶進(jìn)行驗(yàn)證
                  X509AuthenticationProvider 從X509認(rèn)證中獲取用戶信息驗(yàn)證身份
                  TestingAuthenticationProvider 單元測(cè)試時(shí)使用

                  每個(gè)認(rèn)證者會(huì)對(duì)自己指定的證明信息進(jìn)行認(rèn)證,如DaoAuthenticationProvider僅對(duì)UsernamePasswordAuthenticationToken這個(gè)證明信息進(jìn)行認(rèn)證。

          <bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager">
                  <property name="providers">
                      <list>
                          <ref local="daoAuthenticationProvider"/>
                          <ref local="anonymousAuthenticationProvider"/>
                          <ref local="rememberMeAuthenticationProvider"/>
                      </list>
                  </property>
          </bean>


          2) daoAuthenticationProvider
          進(jìn)行簡(jiǎn)單的基于數(shù)據(jù)庫(kù)的身份驗(yàn) 證。DaoAuthenticationProvider獲取數(shù)據(jù)庫(kù)中的賬號(hào)密碼并進(jìn)行匹配,若成功則在通過(guò)用戶身份的同時(shí)返回一個(gè)包含授權(quán)信息的 Authentication對(duì)象,否則身份驗(yàn)證失敗,拋出一個(gè)AuthenticatiionException。

              <bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
                  <property name="userDetailsService" ref="jdbcDaoImpl"/>
                  <property name="userCache" ref="userCache"/>
                  <property name="passwordEncoder" ref="passwordEncoder"/>
             </bean>


          3) passwordEncoder
          使用加密器對(duì)用戶輸入的明文進(jìn)行加密。Acegi提供了三種加密器:
          PlaintextPasswordEncoder—默認(rèn),不加密,返回明文.
          ShaPasswordEncoder—哈希算法(SHA)加密
          Md5PasswordEncoder—消息摘要(MD5)加密

          <bean id="passwordEncoder" class="org.acegisecurity.providers.encoding.Md5PasswordEncoder"/>


          4) jdbcDaoImpl
          用于在數(shù)據(jù)中獲取用戶信息。 acegi提供了用戶及授權(quán)的表結(jié)構(gòu),但是您也可以自己來(lái)實(shí)現(xiàn)。通過(guò)usersByUsernameQuery這個(gè)SQL得到你的(用戶ID,密碼,狀態(tài) 信息);通過(guò)authoritiesByUsernameQuery這個(gè)SQL得到你的(用戶ID,授權(quán)信息)

           
          <bean id="jdbcDaoImpl"
          class="org.acegisecurity.userdetails.jdbc.JdbcDaoImpl">
                 
          <property name="dataSource"
          ref="dataSource"/>
                  <property
          name="usersByUsernameQuery">
                     
          <value>select loginid,passwd,1 from users where loginid =
          ?</value>
                 
          </property>
                  <property
          name="authoritiesByUsernameQuery">
                     
          <value>select u.loginid,p.name from users u,roles r,permissions
          p,user_role ur,role_permis rp where u.id=ur.user_id and r.id=ur.role_id and
          p.id=rp.permis_id
          and
                         
          r.id=rp.role_id and p.status='1' and
          u.loginid=?</value>
                 
          </property>
          </bean>

          5) userCache &  resourceCache
          緩存用戶和資源相對(duì)應(yīng)的權(quán)限信息。每當(dāng)請(qǐng)求一個(gè)受保護(hù)資源時(shí),daoAuthenticationProvider就會(huì)被調(diào)用以獲取用戶授權(quán)信息。如果每次都從數(shù)據(jù)庫(kù)獲取的話,那代價(jià)很高,對(duì)于不常改變的用戶和資源信息來(lái)說(shuō),最好是把相關(guān)授權(quán)信息緩存起來(lái)。(詳見(jiàn) 2.6.3 資源權(quán)限定義擴(kuò)展 )
          userCache提供了兩種實(shí)現(xiàn): NullUserCache和EhCacheBasedUserCache, NullUserCache實(shí)際上就是不進(jìn)行任何緩存,EhCacheBasedUserCache是使用Ehcache來(lái)實(shí)現(xiàn)緩功能。

              <bean id="userCacheBackend" 
          class="org.springframework.cache.ehcache.EhCacheFactoryBean">
                 
          <property name="cacheManager"
          ref="cacheManager"/>
                 
          <property name="cacheName" value="userCache"/>
              </bean>
              <bean id="userCache"
          class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache"
          autowire="byName">
                  <property
          name="cache" ref="userCacheBackend"/>
             
          </bean>
              <bean id="resourceCacheBackend"
          class="org.springframework.cache.ehcache.EhCacheFactoryBean">
                 
          <property name="cacheManager"
          ref="cacheManager"/>
                 
          <property name="cacheName" value="resourceCache"/>
              </bean>
              <bean id="resourceCache"
          class="org.springside.modules.security.service.acegi.cache.ResourceCache"
          autowire="byName">
                  <property
          name="cache" ref="resourceCacheBackend"/>
              </bean>


          6) basicProcessingFilter
          用于處理HTTP頭的認(rèn)證信息,如從 Spring遠(yuǎn)程協(xié)議(如Hessian和Burlap)或普通的瀏覽器如IE,Navigator的HTTP頭中獲取用戶信息,將他們轉(zhuǎn)交給通過(guò) authenticationManager屬性裝配的認(rèn)證管理器。如果認(rèn)證成功,會(huì)將一個(gè)Authentication對(duì)象放到會(huì)話中,否則,如果認(rèn)證 失敗,會(huì)將控制轉(zhuǎn)交給認(rèn)證入口點(diǎn)(通過(guò)authenticationEntryPoint屬性裝配)

              <bean id="basicProcessingFilter" class="org.acegisecurity.ui.basicauth.BasicProcessingFilter">
                  <property name="authenticationManager" ref="authenticationManager"/>
                  <property name="authenticationEntryPoint" ref="basicProcessingFilterEntryPoint"/>
              </bean>

          7) basicProcessingFilterEntryPoint
          通過(guò)向?yàn)g覽器發(fā)送一個(gè)HTTP401(未授權(quán))消息,提示用戶登錄。
          處理基于HTTP的授權(quán)過(guò)程, 在當(dāng)驗(yàn)證過(guò)程出現(xiàn)異常后的"去向",通常實(shí)現(xiàn)轉(zhuǎn)向、在response里加入error信息等功能。

           <bean 
          id="basicProcessingFilterEntryPoint"
          class="org.acegisecurity.ui.basicauth.BasicProcessingFilterEntryPoint">
                 
          <property name="realmName" value="SpringSide Realm"/>
          </bean>

          8) authenticationProcessingFilterEntryPoint
          當(dāng)拋 出AccessDeniedException時(shí),將用戶重定向到登錄界面。屬性loginFormUrl配置了一個(gè)登錄表單的URL,當(dāng)需要用戶登錄 時(shí),authenticationProcessingFilterEntryPoint會(huì)將用戶重定向到該URL

           
          <bean id="authenticationProcessingFilterEntryPoint"
          class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
                 
          <property
          name="loginFormUrl">
                     
          <value>/security/login.jsp</value>
                 
          </property>
                  <property
          name="forceHttps" value="false"/>
          </bean>

          2.2.3 HTTP安全請(qǐng)求

          1) httpSessionContextIntegrationFilter
          每次 request前 HttpSessionContextIntegrationFilter從Session中獲取Authentication對(duì)象,在request完 后, 又把Authentication對(duì)象保存到Session中供下次request使用,此filter必須其他Acegi filter前使用,使之能跨越多個(gè)請(qǐng)求。

          <bean id="httpSessionContextIntegrationFilter" class="org.acegisecurity.context.HttpSessionContextIntegrationFilter"></bean>
              <bean id="httpRequestAccessDecisionManager" class="org.acegisecurity.vote.AffirmativeBased">
                  <property name="allowIfAllAbstainDecisions" value="false"/>
                  <property name="decisionVoters">
                      <list>
                          <ref bean="roleVoter"/>
                      </list>
                  </property>
          </bean>


          2) httpRequestAccessDecisionManager
          經(jīng)過(guò)投票機(jī)制來(lái) 決定是否可以訪問(wèn)某一資源(URL或方法)。allowIfAllAbstainDecisions為false時(shí)如果有一個(gè)或以上的 decisionVoters投票通過(guò),則授權(quán)通過(guò)。可選的決策機(jī)制有ConsensusBased和UnanimousBased

              <bean id="httpRequestAccessDecisionManager" class="org.acegisecurity.vote.AffirmativeBased">
                  <property name="allowIfAllAbstainDecisions" value="false"/>
                  <property name="decisionVoters">
                      <list>
                          <ref bean="roleVoter"/>
                      </list>
                  </property>
              </bean>


          3) roleVoter
             必須是以rolePrefix設(shè)定的value開(kāi)頭的權(quán)限才能進(jìn)行投票,如AUTH_ , ROLE_

              <bean id="roleVoter" class="org.acegisecurity.vote.RoleVoter">
                  <property name="rolePrefix" value="AUTH_"/>
             </bean>

          4)exceptionTranslationFilter
          異常轉(zhuǎn)換過(guò)濾器,主要是處理AccessDeniedException和AuthenticationException,將給每個(gè)異常找到合適的"去向" 

             <bean id="exceptionTranslationFilter" class="org.acegisecurity.ui.ExceptionTranslationFilter">
                  <property name="authenticationEntryPoint" ref="authenticationProcessingFilterEntryPoint"/>
              </bean>

          5) authenticationProcessingFilter
          和servlet spec差不多,處理登陸請(qǐng)求.當(dāng)身份驗(yàn)證成功時(shí),AuthenticationProcessingFilter會(huì)在會(huì)話中放置一個(gè)Authentication對(duì)象,并且重定向到登錄成功頁(yè)面
                   authenticationFailureUrl定義登陸失敗時(shí)轉(zhuǎn)向的頁(yè)面
                   defaultTargetUrl定義登陸成功時(shí)轉(zhuǎn)向的頁(yè)面
                   filterProcessesUrl定義登陸請(qǐng)求的頁(yè)面
                   rememberMeServices用于在驗(yàn)證成功后添加cookie信息

              <bean id="authenticationProcessingFilter" class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
                  <property name="authenticationManager" ref="authenticationManager"/>
                  <property name="authenticationFailureUrl">
                      <value>/security/login.jsp?login_error=1</value>
                  </property>
                  <property name="defaultTargetUrl">
                      <value>/admin/index.jsp</value>
                  </property>
                  <property name="filterProcessesUrl">
                      <value>/j_acegi_security_check</value>
                  </property>
                  <property name="rememberMeServices" ref="rememberMeServices"/>
              </bean>

          6) filterInvocationInterceptor
          在執(zhí)行轉(zhuǎn)向url前檢查 objectDefinitionSource中設(shè)定的用戶權(quán)限信息。首先,objectDefinitionSource中定義了訪問(wèn)URL需要的屬性 信息(這里的屬性信息僅僅是標(biāo)志,告訴accessDecisionManager要用哪些voter來(lái)投票)。然后, authenticationManager掉用自己的provider來(lái)對(duì)用戶的認(rèn)證信息進(jìn)行校驗(yàn)。最后,有投票者根據(jù)用戶持有認(rèn)證和訪問(wèn)url需要的 屬性,調(diào)用自己的voter來(lái)投票,決定是否允許訪問(wèn)。

              <bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
                  <property name="authenticationManager" ref="authenticationManager"/>
                  <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
                  <property name="objectDefinitionSource" ref="filterDefinitionSource"/>
              </bean>


          7) filterDefinitionSource (詳見(jiàn) 2.6.3 資源權(quán)限定義擴(kuò)展)
          自定義DBFilterInvocationDefinitionSource從數(shù)據(jù)庫(kù)和cache中讀取保護(hù)資源及其需要的訪問(wèn)權(quán)限信息 

          <bean id="filterDefinitionSource" class="org.springside.modules.security.service.acegi.DBFilterInvocationDefinitionSource">
                  <property name="convertUrlToLowercaseBeforeComparison" value="true"/>
                  <property name="useAntPath" value="true"/>
                  <property name="acegiCacheManager" ref="acegiCacheManager"/>
          </bean>

          2.2.4 方法調(diào)用安全控制

          (詳見(jiàn) 2.6.3 資源權(quán)限定義擴(kuò)展)

          1) methodSecurityInterceptor
          在執(zhí)行方法前進(jìn)行攔截,檢查用戶權(quán)限信息
          2) methodDefinitionSource
          自定義MethodDefinitionSource從cache中讀取權(quán)限

             <bean id="methodSecurityInterceptor" class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
                  <property name="authenticationManager" ref="authenticationManager"/>
                  <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
                  <property name="objectDefinitionSource" ref="methodDefinitionSource"/>
              </bean>
              <bean id="methodDefinitionSource" class="org.springside.modules.security.service.acegi.DBMethodDefinitionSource">
                  <property name="acegiCacheManager" ref="acegiCacheManager"/>
              </bean>

          2.3 Jcaptcha驗(yàn)證碼

          采用 http://jcaptcha.sourceforge.net 作為通用的驗(yàn)證碼方案,請(qǐng)參考SpringSide中的例子,或網(wǎng)上的:
          http://www.coachthrasher.com/page/blog?entry=jcaptcha_with_appfuse

          差沙在此過(guò)程中又發(fā)現(xiàn)acegi logout filter的錯(cuò)誤,進(jìn)行了修正。

          另外它默認(rèn)提供的圖片比較難認(rèn),我們custom了一個(gè)美觀一點(diǎn)的版本。

           

          三 Acegi安全系統(tǒng)擴(kuò)展

                相信side對(duì)Acegi的擴(kuò)展會(huì)給你耳目一新的感覺(jué),提供完整的擴(kuò)展功能,管理界面,中文注釋和靠近企業(yè)的安全策略。side只對(duì)Acegi不符合企業(yè)應(yīng)用需要的功能進(jìn)行擴(kuò)展,盡量不改動(dòng)其余部分來(lái)實(shí)現(xiàn)全套權(quán)限管理功能,以求能更好地適應(yīng)Acegi升級(jí)。

           

          3.1 基于角色的權(quán)限控制(RBAC)

              Acegi 自帶的 sample 表設(shè)計(jì)很簡(jiǎn)單: users表{username,password,enabled} authorities表{username,authority},這樣簡(jiǎn)單的設(shè)計(jì)無(wú)法適應(yīng)復(fù)雜的權(quán)限需求,故SpringSide選用RBAC模型對(duì) 權(quán)限控制數(shù)據(jù)庫(kù)表進(jìn)行擴(kuò)展。 RBAC引入了ROLE的概念,使User(用戶)和Permission(權(quán)限)分離,一個(gè)用戶擁有多個(gè)角色,一個(gè)角色擁 有有多個(gè)相應(yīng)的權(quán)限,從而減少了權(quán)限管理的復(fù)雜度,可更靈活地支持安全策略。

              同時(shí),我們也引入了resource(資源)的概念,一個(gè)資源對(duì)應(yīng)多個(gè)權(quán)限,資源分為ACL,URL,和FUNTION三種。注意,URL和FUNTION的權(quán)限命名需要以AUTH_開(kāi)頭才會(huì)有資格參加投票, 同樣的ACL權(quán)限命名需要ACL_開(kāi)頭。


          3.2 管理和使用EhCache

          3.2.1 設(shè)立緩存

          在SpringSide里的 Acegi 擴(kuò)展使用 EhCache 就作為一種緩存解決方案,以緩存用戶和資源的信息和相對(duì)應(yīng)的權(quán)限信息。

          首先需要一個(gè)在classpath的 ehcache.xml 文件,用于配置 EhCache。

          <ehcache>
                 <defaultCache
                      maxElementsInMemory="10000"
                      eternal="false"
                      overflowToDisk="true"
                      timeToIdleSeconds="0"
                      timeToLiveSeconds="0"
                      diskPersistent="false"
                     diskExpiryThreadIntervalSeconds= "120"/>
              <!-- acegi cache-->
              <cache name="userCache"
                     maxElementsInMemory="10000"
                     eternal="true"
                    overflowToDisk= "true"/>
              <!-- acegi cache-->
              <cache name="resourceCache"
                     maxElementsInMemory="10000"
                     eternal="true"
                     overflowToDisk="true"/>
          </ehcache>

               maxElementsInMemory設(shè)定了允許在Cache中存放的數(shù)據(jù)數(shù)目,eternal設(shè)定Cache是否會(huì)過(guò)期, overflowToDisk設(shè)定內(nèi)存不足的時(shí)候緩存到硬盤(pán),timeToIdleSeconds和timeToLiveSeconds設(shè)定緩存游離時(shí)間 和生存時(shí)間,diskExpiryThreadIntervalSeconds設(shè)定緩存在硬盤(pán)上的生存時(shí)間,注意當(dāng)eternal="true"時(shí), timeToIdleSeconds,timeToLiveSeconds和diskExpiryThreadIntervalSeconds都是無(wú)效 的。

          <defaultCache>是除 制定的Cache外其余所有Cache的設(shè)置,針對(duì)Acegi 的情況, 專(zhuān)門(mén)設(shè)置了userCache和resourceCache,都設(shè)為永不過(guò)期。在applicationContext-acegi- security.xml中相應(yīng)的調(diào)用是

          <bean id="userCacheBackend" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
                  <property name="cacheManager" ref="cacheManager"/>
                  <property name="cacheName" value=" userCache"/>
              </bean>
              <bean id="userCache" class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache" autowire="byName">
                  <property name="cache" ref="userCacheBackend"/>
              </bean>
              <bean id="resourceCacheBackend" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
                  <property name="cacheManager" ref="cacheManager"/>
                  <property name="cacheName" value=" resourceCache"/>
              </bean>
              <bean id="resourceCache" class="org.springside.modules.security.service.acegi.cache.ResourceCache" autowire="byName">
                  <property name="cache" ref="resourceCacheBackend"/>
              </bean>
          <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>

          "cacheName" 就是設(shè)定在ehcache.xml 中相應(yīng)Cache的名稱(chēng)。

          userCache使用的是Acegi 的EhCacheBasedUserCache(實(shí)現(xiàn)了UserCache接口), resourceCache是SpringSide的擴(kuò)展類(lèi)

          public interface UserCache   {
              public UserDetails getUserFromCache (String username);

              public void putUserInCache (UserDetails user);

              public void removeUserFromCache (String username);
          }

          public class ResourceCache   {
              public ResourceDetails getAuthorityFromCache (String resString) {...   }
              public void putAuthorityInCache (ResourceDetails resourceDetails) {...  }
           
             public void removeAuthorityFromCache (String resString) {... }
              public List getUrlResStrings() {... }
              public List getFunctions() {.. }
          }

          UserCache 就是通過(guò)EhCache對(duì)UserDetails 進(jìn)行緩存管理, 而ResourceCache 是對(duì)ResourceDetails 類(lèi)進(jìn)行緩存管理


          public interface UserDetails   extends Serializable {
              public boolean isAccountNonExpired();
              public boolean isAccountNonLocked();

              public GrantedAuthority[] getAuthorities();

              public boolean isCredentialsNonExpired();

              public boolean isEnabled();

              public String getPassword();

              public String getUsername();
          }

          public interface ResourceDetails   extends Serializable {
              public String getResString();

              public String getResType();

              public GrantedAuthority[] getAuthorities();
          }

          UserDetails 包含用戶信息和相應(yīng)的權(quán)限,ResourceDetails 包含資源信息和相應(yīng)的權(quán)限。


          public interface GrantedAuthority     {
              public String getAuthority ();
          }

               GrantedAuthority 就是權(quán)限信息,在Acegi 的 sample 里GrantedAuthority 的信息如ROLE_USER, ROLE_SUPERVISOR, ACL_CONTACT_DELETE, ACL_CONTACT_ADMIN等等,網(wǎng)上也有很多例子把角色作為GrantedAuthority ,但事實(shí)上看看ACL 就知道, Acegi本身根本就沒(méi)有角色這個(gè)概念,GrantedAuthority 包含的信息應(yīng)該是權(quán)限,對(duì)于非ACL的權(quán)限用 AUTH_ 開(kāi)頭更為合理, 如SpringSide里的 AUTH_ADMIN_LOGIN, AUTH_BOOK_MANAGE 等等。


          3.2.2 管理緩存


               使用AcegiCacheManager對(duì)userCache和resourceCache進(jìn)行統(tǒng)一緩存管理。當(dāng)在后臺(tái)對(duì)用戶信息進(jìn)行修改或賦權(quán)的時(shí)候, 在更新數(shù)據(jù)庫(kù)同時(shí)就會(huì)調(diào)用acegiCacheManager相應(yīng)方法, 從數(shù)據(jù)庫(kù)中讀取數(shù)據(jù)并替換cache中相應(yīng)部分,使cache與數(shù)據(jù)庫(kù)同步。

          public class AcegiCacheManager extends BaseService {
              private ResourceCache resourceCache ;
              private UserCache userCache ;
              /**
               * 修改User時(shí)更改userCache
               */

              public void modifyUserInCache (User user, String orgUsername) {...    }
              /**
               * 修改Resource時(shí)更改resourceCache
               */

              public void modifyResourceInCache (Resource resource, String orgResourcename) {...    }
              /**
               * 修改權(quán)限時(shí)同時(shí)修改userCache和resourceCache
               */

              public void modifyPermiInCache (Permission permi, String orgPerminame) {...  }
              /**
               * User授予角色時(shí)更改userCache
               */
              public void authRoleInCache (User user) {...    }
              /**
               * Role授予權(quán)限時(shí)更改userCache和resourceCache
               */

              public void authPermissionInCache (Role role) {...  }
              /**
               * Permissioni授予資源時(shí)更改resourceCache
               */

              public void authResourceInCache (Permission permi) {...  }
              /**
               * 初始化userCache
               */

              public void initUserCache () {...  }
              /**
               * 初始化resourceCache
               */

              public void initResourceCache () {... }
              /**
               * 獲取所有的url資源
               */

              public List getUrlResStrings () {...  }
              /**
               * 獲取所有的Funtion資源
               */

              public List getFunctions () {...  }
              /**
               * 根據(jù)資源串獲取資源
               */

              public ResourceDetails getAuthorityFromCache (String resString) {...  }
            
           ......


          }

           


          3.3 資源權(quán)限定義擴(kuò)展


               Acegi給出的sample里,資源權(quán)限對(duì)照關(guān)系是配置在xml中的,試想一下如果你的企業(yè)安全應(yīng)用有500個(gè)用戶,100個(gè)角色權(quán)限的時(shí)候,維護(hù)這個(gè)xml將是個(gè)繁重?zé)o比的工作,如何動(dòng)態(tài)更改用戶權(quán)限更是個(gè)頭痛的問(wèn)題。


             <bean id="contactManagerSecurity" class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
                <property name="authenticationManager"><ref bean="authenticationManager"/></property>
                <property name="accessDecisionManager"><ref local="businessAccessDecisionManager"/></property>
                <property name="afterInvocationManager"><ref local="afterInvocationManager"/></property>
                <property name="objectDefinitionSource">
                   <value>
                      sample.contact.ContactManager.create=ROLE_USER
                      sample.contact.ContactManager.getAllRecipients=ROLE_USER
                      sample.contact.ContactManager.getAll=ROLE_USER,AFTER_ACL_COLLECTION_READ
                      sample.contact.ContactManager.getById=ROLE_USER,AFTER_ACL_READ
                      sample.contact.ContactManager.delete=ACL_CONTACT_DELETE
                      sample.contact.ContactManager.deletePermission=ACL_CONTACT_ADMIN
                      sample.contact.ContactManager.addPermission=ACL_CONTACT_ADMIN
                   </value>
                </property>
             </bean>

            <bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
                <property name="authenticationManager"><ref bean="authenticationManager"/></property>
                <property name="accessDecisionManager"><ref local="httpRequestAccessDecisionManager"/></property>
                <property name="objectDefinitionSource">
                   <value>
                 CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
                 PATTERN_TYPE_APACHE_ANT
                 /index.jsp=ROLE_ANONYMOUS,ROLE_USER
                 /hello.htm=ROLE_ANONYMOUS,ROLE_USER
                 /logoff.jsp=ROLE_ANONYMOUS,ROLE_USER
                 /switchuser.jsp=ROLE_SUPERVISOR
                 /j_acegi_switch_user=ROLE_SUPERVISOR
                 /acegilogin.jsp*=ROLE_ANONYMOUS,ROLE_USER
               /**=ROLE_USER
                   </value>
                </property>
             </bean>

           對(duì)如此不Pragmatic的做法,SpringSide進(jìn)行了擴(kuò)展, 讓Acegi 能動(dòng)態(tài)讀取數(shù)據(jù)庫(kù)中的權(quán)限資源關(guān)系。


          3.3.1 Aop Invocation Authorization


              <bean id="methodSecurityInterceptor" class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
                  <property name="authenticationManager" ref="authenticationManager"/>
                  <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
                  <property name="objectDefinitionSource" ref="methodDefinitionSource"/>
              </bean>
              <bean id="methodDefinitionSource" class="org.springside.security.service.acegi.DBMethodDefinitionSource">
                  <property name="acegiCacheManager" ref="acegiCacheManager"/>
              </bean>

               研究下Aceig的源碼,ObjectDefinitionSource的實(shí)際作用是返回一個(gè)ConfigAttributeDefinition對(duì)象,而Acegi Sample 的方式是用MethodDefinitionSourceEditor把xml中的文本Function資源權(quán)限對(duì)應(yīng)關(guān)系信息加載到MethodDefinitionMap ( MethodDefinitionSource 的實(shí)現(xiàn)類(lèi) )中, 再組成ConfigAttributeDefinition,而我們的擴(kuò)展目標(biāo)是從緩存中讀取信息來(lái)組成ConfigAttributeDefinition。


               MethodSecurityInterceptor是通過(guò)調(diào)用AbstractMethodDefinitionSource的lookupAttributes(method)方法獲取ConfigAttributeDefinition。所以我們需要實(shí)現(xiàn)自己的ObjectDefinitionSource,繼承AbstractMethodDefinitionSource并實(shí)現(xiàn)其lookupAttributes方法,從緩存中讀取資源權(quán)限對(duì)應(yīng)關(guān)系組成并返回ConfigAttributeDefinition即可。SpringSide中的DBMethodDefinitionSource類(lèi)的部分實(shí)現(xiàn)如下 :


          public class DBMethodDefinitionSource extends AbstractMethodDefinitionSource {
          ......
              protected ConfigAttributeDefinition lookupAttributes(Method mi) {
                  Assert.notNull(mi, "lookupAttrubutes in the DBMethodDefinitionSource is null");
                  String methodString = mi.getDeclaringClass().getName() + "." + mi.getName();
                  if (!acegiCacheManager.isCacheInitialized()) {
                      //初始化Cache
                      acegiCacheManager.initResourceCache();
                  }
                  //獲取所有的function
                  List methodStrings = acegiCacheManager.getFunctions();
                  Set auths = new HashSet();
                  //取權(quán)限的合集
                  for (Iterator iter = methodStrings.iterator(); iter.hasNext();) {
                      String mappedName = (String) iter.next();
                      if (methodString.equals(mappedName)
                              || isMatch(methodString, mappedName)) {
                          ResourceDetails resourceDetails = acegiCacheManager.getAuthorityFromCache(mappedName);
                          if (resourceDetails == null) {
                              break;
                          }
                          GrantedAuthority[] authorities = resourceDetails.getAuthorities();
                          if (authorities == null || authorities.length == 0) {
                              break;
                          }
                          auths.addAll(Arrays.asList(authorities));
                      }
                  }
                  if (auths.size() == 0)
                      return null;
                  ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor();
                  String authoritiesStr = " ";
                  for (Iterator iter = auths.iterator(); iter.hasNext();) {
                      GrantedAuthority authority = (GrantedAuthority) iter.next();
                      authoritiesStr += authority.getAuthority() + ",";
                  }
                  String authStr = authoritiesStr.substring(0, authoritiesStr.length() - 1);
                  configAttrEditor.setAsText(authStr);
                 //組裝并返回ConfigAttributeDefinition
                  return (ConfigAttributeDefinition) configAttrEditor.getValue();
              }
              ......
          }

          要注意幾點(diǎn)的是:
          1) 初始化Cache是比較浪費(fèi)資源的,所以SpringSide中除第一次訪問(wèn)外的Cache的更新是針對(duì)性更新。


          2) 因?yàn)閙ethod采用了匹配方式(詳見(jiàn) isMatch() 方法) , 即對(duì)于*Book和save*這兩個(gè)資源來(lái)說(shuō),只要當(dāng)前訪問(wèn)方法是Book結(jié)尾或以save開(kāi)頭都算匹配得上,所以應(yīng)該取這些能匹配上的資源的相對(duì)應(yīng)的權(quán)限的合集。


          3) 使用ConfigAttributeEditor 能更方便地組裝ConfigAttributeDefinition。


          3.3.2 Filter Invocation Authorization


              <bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
                  <property name="authenticationManager" ref="authenticationManager"/>
                  <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
                  <property name="objectDefinitionSource" ref="filterDefinitionSource"/>
              </bean>

              <bean id="filterDefinitionSource" class="org.springside.security.service.acegi.DBFilterInvocationDefinitionSource">
                  <property name="convertUrlToLowercaseBeforeComparison" value="true"/>
                  <property name="useAntPath" value="true"/>
                  <property name="acegiCacheManager" ref="acegiCacheManager"/>
              </bean>

               PathBasedFilterInvocationDefinitionMap和RegExpBasedFilterInvocationDefinitionMap都是 FilterInvocationDefinitionSource的實(shí)現(xiàn)類(lèi),當(dāng)PATTERN_TYPE_APACHE_ANT字符串匹配上時(shí)時(shí),FilterInvocationDefinitionSourceEditor 選用PathBasedFilterInvocationDefinitionMap 把xml中的文本URL資源權(quán)限對(duì)應(yīng)關(guān)系信息加載。


               FilterSecurityInterceptor通過(guò)FilterInvocationDefinitionSource的lookupAttributes(url)方法獲取ConfigAttributeDefinition。 所以,我們可以通過(guò)繼承FilterInvocationDefinitionSource的抽象類(lèi)AbstractFilterInvocationDefinitionSource,并實(shí)現(xiàn)其lookupAttributes方法,從緩存中讀取URL資源權(quán)限對(duì)應(yīng)關(guān)系即可。SpringSide的DBFilterInvocationDefinitionSource類(lèi)部分實(shí)現(xiàn)如下:


          public class DBFilterInvocationDefinitionSource extends AbstractFilterInvocationDefinitionSource {

          ......
              public ConfigAttributeDefinition lookupAttributes(String url) {
                  if (!acegiCacheManager.isCacheInitialized()) {
                      acegiCacheManager.initResourceCache();
                  }

                  if (isUseAntPath()) {
                      // Strip anything after a question mark symbol, as per SEC-161.
                      int firstQuestionMarkIndex = url.lastIndexOf("?");
                      if (firstQuestionMarkIndex != -1) {
                          url = url.substring(0, firstQuestionMarkIndex);
                      }
                  }
                  List urls = acegiCacheManager.getUrlResStrings();
                  //URL資源倒敘排序
                  Collections.sort(urls);
                  Collections.reverse(urls);
          //是否先全部轉(zhuǎn)為小寫(xiě)再比較
                  if (convertUrlToLowercaseBeforeComparison) {
                      url = url.toLowerCase();
                  }
                  GrantedAuthority[] authorities = new GrantedAuthority[0];
                  for (Iterator iterator = urls.iterator(); iterator.hasNext();) {
                      String resString = (String) iterator.next();
                      boolean matched = false;
          //可選擇使用AntPath和Perl5兩種不同匹配模式
                      if (isUseAntPath()) {
                          matched = pathMatcher.match(resString, url);
                      } else {
                          Pattern compiledPattern;
                          Perl5Compiler compiler = new Perl5Compiler();
                          try {
                              compiledPattern = compiler.compile(resString,
                                      Perl5Compiler.READ_ONLY_MASK);
                          } catch (MalformedPatternException mpe) {
                              throw new IllegalArgumentException(
                                      "Malformed regular expression: " + resString);
                          }
                          matched = matcher.matches(url, compiledPattern);
                      }
                      if (matched) {
                          ResourceDetails rd = acegiCacheManager.getAuthorityFromCache(resString);
                          authorities = rd.getAuthorities();
                          break;
                      }
                  }
                  if (authorities.length > 0) {
                      String authoritiesStr = " ";
                      for (int i = 0; i < authorities.length; i++) {
                          authoritiesStr += authorities[i].getAuthority() + ",";
                      }
                      String authStr = authoritiesStr.substring(0, authoritiesStr
                              .length() - 1);
                      ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor();
                      configAttrEditor.setAsText(authStr);
                      return (ConfigAttributeDefinition) configAttrEditor.getValue();
                  }
                  return null;
              }

          ......
           }

          繼承AbstractFilterInvocationDefinitionSource注意幾點(diǎn):
          1)  需要先把獲取回來(lái)的URL資源按倒序派序,以達(dá)到 a/b/c/d.* 在 a/.* 之前的效果(詳見(jiàn) Acegi sample 的applicationContext-acegi-security.xml 中的filterInvocationInterceptor的注釋),為的是更具體的URL可以先匹配上,而獲取具體URL的權(quán)限,如a/b/c/d.*權(quán)限AUTH_a, AUTH_b 才可查看,  a/.* 需要權(quán)限AUTH_a 才可查看,則如果當(dāng)前用戶只擁有權(quán)限AUTH_b,則他只可以查看a/b/c/d.jsp 而不能察看a/d.jsp。


          2) 基于上面的原因,故第一次匹配上的就是當(dāng)前所需權(quán)限,而不是取權(quán)限的合集。


          3) 可以選用AntPath 或 Perl5 的資源匹配方式,感覺(jué)AntPath匹配方式基本足夠。


          4) Filter 權(quán)限控制比較適合于較粗顆粒度的權(quán)限,如設(shè)定某個(gè)模塊下的頁(yè)面是否能訪問(wèn)等,對(duì)于具體某個(gè)操作如增刪修改,是否能執(zhí)行,用Method  Invocation 會(huì)更佳些,所以注意兩個(gè)方面一起控制效果更好


           


          3.4 授權(quán)操作


               RBAC模型中有不少多對(duì)多的關(guān)系,這些關(guān)系都能以一個(gè)中間表的形式來(lái)存放,而Hibernate中可以不建這中間表對(duì)應(yīng)的hbm.xml , 以資源與權(quán)限的配置為例,如下:


          <hibernate-mapping package="org.springside.modules.security.domain">
              <class name="Permission" table="PERMISSIONS" dynamic-insert="true" dynamic-update="true">
                  <cache usage="nonstrict-read-write"/>
                  <id name="id" column="ID">
                      <generator class="native"/>
                  </id>
                  <property name="name" column="NAME" not-null="true"/>
                  <property name="descn" column="DESCN"/>
                  <property name="operation" column="OPERATION"/>
                  <property name="status" column="STATUS"/>
                  <set name="roles" table="ROLE_PERMIS" lazy="true" inverse="true" cascade="save-update" batch-size="5">
                      <key>
                          <column name="PERMIS_ID" not-null="true"/>
                      </key>
                      <many-to-many class="Role" column="ROLE_ID" outer-join="auto"/>
                  </set>
                  <set name="resources" table="PERMIS_RESC" lazy="true" inverse="false" cascade="save-update" batch-size="5">
                      <key>
                          <column name="PERMIS_ID" not-null="true"/>
                      </key>
                      <many-to-many class="Resource" column="RESC_ID"/>
                  </set>
              </class>
          </hibernate-mapping>

          <hibernate-mapping package="org.springside.modules.security.domain">
              <class name="Resource" table="RESOURCES" dynamic-insert="true" dynamic-update="true">
                  <cache usage="nonstrict-read-write"/>
                  <id name="id" column="ID">
                      <generator class="native"/>
                  </id>
                  <property name="name" column="NAME" not-null="true"/>
                  <property name="resType" column="RES_TYPE" not-null="true"/>
                  <property name="resString" column="RES_STRING" not-null="true"/>
                  <property name="descn" column="DESCN"/>
                  <set name="permissions" table="PERMIS_RESC" lazy="true" inverse="true" cascade="save-update" batch-size="5">
                      <key>
                          <column name="RESC_ID" not-null="true"/>
                      </key>
                      <many-to-many class="Permission" column="PERMIS_ID" outer-join="auto"/>
                  </set>
              </class>
          </hibernate-mapping>

          配置時(shí)注意幾點(diǎn):


          1) 因?yàn)槭欠峙淠硞€(gè)權(quán)限的資源,所以權(quán)限是主控方,把inverse設(shè)為false,資源是被控方inverse設(shè)為true


          2) cascade是"save-update",千萬(wàn)別配成delete


          3) 只需要 permission.getResources().add(resource), permission.getResources()..remove(resource) 即可很方便地完成授權(quán)和取消授權(quán)操作


           


          四 Acegi ACL使用


          4.1 基本概念


                在google中搜索'acl'會(huì)找到很多相關(guān)的介紹,而且涉及的范圍也特別廣泛。ACL是(Access Control List)的縮寫(xiě),顧名思義,ACL是‘訪問(wèn)控制列表’的意思。通俗點(diǎn)說(shuō),ACL保存了所有用戶或角色對(duì)資源的訪問(wèn)權(quán)限。最典型的ACL實(shí)現(xiàn)是流行操作系統(tǒng)(window, unix)的文件訪問(wèn)控制系統(tǒng),精確定義了某個(gè)用戶或角色對(duì)某個(gè)特定文件的讀、寫(xiě)、執(zhí)行等權(quán)限,更通俗的例子是可以定義某個(gè)管理員只能管一部分的訂單,而另一個(gè)管理員只能管另一部分的。


          4.2 Acegi ACL配置


          Acegi好早就實(shí)現(xiàn)了ACL(好像是0.5),但是使用起來(lái)確實(shí)有點(diǎn)麻煩,所以用的不是太廣泛。這里簡(jiǎn)單的說(shuō)明一下使用方法,希望有更多的朋友來(lái)試試。

          首先要理解Acegi里面Voter的概念,ACL正是在一個(gè)Voter上擴(kuò)展起來(lái)的。現(xiàn)來(lái)看一下AclVoter的配置。


              <bean id="aclBeanReadVoter" class="org.acegisecurity.vote.BasicAclEntryVoter">
                  
          <property name="processConfigAttribute">
                      
          <value>ACL_READ</value>
                  
          </property>
                  
          <property name="processDomainObjectClass">
                      
          <value>org.springside.modules.security.acl.domain.AclDomainAware</value>
                  
          </property>
                  
          <property name="aclManager">
                      
          <ref local="aclManager"/>
                  
          </property>
                  
          <property name="requirePermission">
                      
          <list>
                          
          <ref local="org.acegisecurity.acl.basic.SimpleAclEntry.ADMINISTRATION"/>
                          
          <ref local="org.acegisecurity.acl.basic.SimpleAclEntry.READ"/>
                      
          </list>
                  
          </property>
              
          </bean>


          1. ACL_READ指的是這個(gè)Voter對(duì)哪些SecurityConfig起作用,我們可以把ACL_READ配置在想要攔截的Method上。比方說(shuō)我們要攔截readOrder這個(gè)方法,以實(shí)現(xiàn)ACL控制,可以這樣配置。
            orderManager.readOrder=ACL_READ

          2. processDomainObjectClass指出哪些DomainObject是要進(jìn)行ACL校驗(yàn)的。

          3. aclManager是一個(gè)比較重要的概念,主要負(fù)責(zé)在權(quán)限列表中根據(jù)用戶和DomainObject取得acl列表。

          4. requirePermission指出要進(jìn)行這個(gè)操作必須具備的acl權(quán)限,比方說(shuō)read操作就必須有ADMINISTRATION或READ兩個(gè)權(quán)限。


          其實(shí)整個(gè)過(guò)程看下來(lái)比較清晰,下面來(lái)看一下AclManager如何配置。


              <!-- ========= ACCESS CONTROL LIST LOOKUP MANAGER DEFINITIONS ========= -->

              
          <bean id="aclManager" class="org.acegisecurity.acl.AclProviderManager">
                  
          <property name="providers">
                      
          <list>
                          
          <ref local="basicAclProvider"/>
                      
          </list>
                  
          </property>
              
          </bean>

              
          <bean id="basicAclProvider" class="org.acegisecurity.acl.basic.BasicAclProvider">
                  
          <property name="basicAclDao">
                      
          <ref local="basicAclExtendedDao"/>
                  
          </property>
              
          </bean>

              
          <bean id="basicAclExtendedDao" class="org.acegisecurity.acl.basic.jdbc.JdbcExtendedDaoImpl">
                  
          <property name="dataSource">
                      
          <ref bean="dataSource"/>
                  
          </property>
              
          </bean>


          很明顯ACLManager繼承了Acegi的一貫風(fēng)格,Provider可以提供多種取得ACL訪問(wèn)列表的途徑,默認(rèn)的是用basicAclProvider在數(shù)據(jù)庫(kù)中取得。既然提到了數(shù)據(jù)庫(kù),那我們就來(lái)看一下Acegi默認(rèn)提供的ACL在數(shù)據(jù)庫(kù)里的保存表結(jié)構(gòu):



          1. acl_object_identity表存放了所有受保護(hù)的domainObject的信息。其中object_identity字段保存了domainObject的class和id,默認(rèn)的保存格式是:domainClass:domainObjectId。

          2. acl_permission 就是ACL權(quán)限列表了,recipient 是用戶或角色信息,mask表示了這個(gè)用戶或角色對(duì)這個(gè)domainObject的訪問(wèn)權(quán)限。注意這些信息的保存格式都是可以根據(jù)自己的需要改變的。


          這樣讀取和刪除的時(shí)候Acegi就能很好的完成攔截工作,但是讀取一個(gè)List的時(shí)候,如何才能把該用戶不能操作的domainObject剔除掉呢?這就需要afterInvocationManager來(lái)完成這個(gè)工作。下面來(lái)看下配置:


              <!-- ============== "AFTER INTERCEPTION" AUTHORIZATION DEFINITIONS =========== -->

              
          <bean id="afterInvocationManager" class="org.acegisecurity.afterinvocation.AfterInvocationProviderManager">
                  
          <property name="providers">
                      
          <list>
                          
          <ref local="afterAclCollectionRead"/>
                      
          </list>
                  
          </property>
              
          </bean>
              
          <!-- Processes AFTER_ACL_COLLECTION_READ configuration settings -->
              
          <bean id="afterAclCollectionRead" class="org.acegisecurity.afterinvocation.BasicAclEntryAfterInvocationCollectionFilteringProvider">
                  
          <property name="aclManager">
                      
          <ref local="aclManager"/>
                  
          </property>
                  
          <property name="requirePermission">
                      
          <list>
                          
          <ref local="org.acegisecurity.acl.basic.SimpleAclEntry.ADMINISTRATION"/>
                          
          <ref local="org.acegisecurity.acl.basic.SimpleAclEntry.READ"/>
                      
          </list>
                  
          </property>
              
          </bean>


          afterAclCollectionRead會(huì)在攔截的方法執(zhí)行結(jié)束的時(shí)候執(zhí)行。主要的作用就是在返回的List中挨個(gè)檢查domainObject的操作權(quán)限,然后根據(jù)requirePermission來(lái)剔除不符合的domainObject。


          4.3 使用RuleEngine設(shè)置的ACL規(guī)則


          在SpringSide里使用了RuleEngine來(lái)設(shè)置ACL規(guī)則,具體規(guī)則見(jiàn)
          bookstore-sample\resources\rules\drl


           


          五 FAQ 


          5.1 FAQ



          1. Q:   能否脫離Spring框架來(lái)使用Acegi?
            A:  雖然Acegi 沒(méi)有要求必須使用Spring Framework,但事實(shí)上Acegi很大程度上利用了Spring的IOC和AOP,很難脫離Spring的單獨(dú)使用。

          2. Q:  Acegi有對(duì)xfire的支持嗎?
            A: 有,詳見(jiàn)http://jira.codehaus.org/browse/XFIRE-389

          3. Q: 為何無(wú)論怎么設(shè)置都返回到登陸頁(yè)面無(wú)法成功登陸?
            A:  檢查登陸頁(yè)面或登陸失敗頁(yè)面是否只有ROLE_ANONYMOUS權(quán)限


          5.2 Acegi 補(bǔ)習(xí)班


          要了解Acegi,首先要了解以下幾個(gè)重要概念:




          1. Authentication
            Authentication對(duì)象包含了principal, credentials 和 authorities(authorities要賦予給principal的),同時(shí)也可以包含一些附加的認(rèn)證請(qǐng)求信息,如TCP/IP地址和Session id等。



          2. SecurityContextHolder
            SecurityContextHolder包含ThreadLocal私有屬性用于存取SecurityContext, SecurityContext包含Authentication私有屬性, 看以下一段程序


            public void getSecurityContextInformations() {
              SecurityContext sc = SecurityContextHolder.getContext();
              Authentication auth = sc.getAuthentication();
              Object principal = auth.getPrincipal();
              if (principal instanceof UserDetails) {
               //用戶密碼
               String password = ((UserDetails) principal).getPassword();
               //用戶名稱(chēng)
               String username = ((UserDetails) principal).getUsername();
               //用戶權(quán)限
               GrantedAuthority[] authorities = ((UserDetails) principal).getAuthorities();
               for (int i = 0; i < authorities.length; i++) {
                String authority = authorities[i].getAuthority();
               }
              }
              Object details = auth.getDetails();
              if (details instanceof WebAuthenticationDetails) {
               //用戶session id
               String SessionId = ((WebAuthenticationDetails) details).getSessionId();
              }
             }



          3. AuthenticationManager
            通過(guò)Providers驗(yàn)證在當(dāng)前 ContextHolder中的Authentication對(duì)象是否合法。

          4. AccessDecissionManager
            經(jīng)過(guò)投票機(jī)制來(lái)審批是否批準(zhǔn)操作

          5. RunAsManager
            當(dāng)執(zhí)行某個(gè)操作時(shí),RunAsManager可選擇性地替換Authentication對(duì)象

          6. Interceptors
            攔截器(如FilterSecurityInterceptor,JoinPoint,MethodSecurityInterceptor等)用于協(xié)調(diào)授權(quán),認(rèn)證等操作



          CREATE TABLE acl_object_identity (
          id 
          IDENTITY NOT NULL,
          object_identity VARCHAR_IGNORECASE(
          250NOT NULL,
          parent_object 
          INTEGER,
          acl_class VARCHAR_IGNORECASE(
          250NOT NULL,
          CONSTRAINT unique_object_identity UNIQUE(object_identity),
          FOREIGN KEY (parent_object) REFERENCES acl_object_identity(id)
          );
          CREATE TABLE acl_permission (
          id 
          IDENTITY NOT NULL,
          acl_object_identity 
          INTEGER NOT NULL,
          recipient VARCHAR_IGNORECASE(
          100NOT NULL,
          mask 
          INTEGER NOT NULL,
          CONSTRAINT unique_recipient UNIQUE(acl_object_identity, recipient),
          FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity(id)
          );


          posted on 2008-07-15 15:50 找個(gè)美女做老婆 閱讀(4121) 評(píng)論(0)  編輯  收藏


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           

          導(dǎo)航

          統(tǒng)計(jì)

          公告

          本blog已經(jīng)搬到新家了, 新家:www.javaly.cn
           http://www.javaly.cn

          常用鏈接

          留言簿(6)

          隨筆檔案

          文章檔案

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 郯城县| 定州市| 乌拉特前旗| 绥德县| 宿迁市| 双峰县| 泰州市| 上思县| 苏尼特右旗| 安图县| 视频| 文山县| 南投市| 定兴县| 大庆市| 临武县| 云浮市| 隆回县| 霍林郭勒市| 波密县| 泾川县| 图木舒克市| 汉寿县| 湖口县| 论坛| 西青区| 武威市| 静宁县| 钦州市| 隆德县| 尼木县| 郓城县| 营口市| 广元市| 溆浦县| 波密县| 太仆寺旗| 于田县| 乐亭县| 上林县| 栾城县|