基於Spring Security2與 Ext 的權限管理設計與實現

一、Spring Security介紹

 

Spring Security的前身Acegi,其配置及使用相對來說複雜一些,因爲要配置的東西比較多,Sprng Security簡化了以前的配置。大家有興趣可以多多瞭解以前的版本,因爲很多細節在前面的版本可以看得比較清楚,後面的版本需要看源代碼才知道其實現的原理了。

基於角色的設計與實現是絕大部分系統中比較常見的權限管理方式,對權限進行分組進行管理有助於減少權限管理的複雜程度。

Spring Security目前提供了三種權限的管理方式:

一、    基於URL的攔截方式
二、    基於方法的AOP攔截方式
三、    基於數據的權限攔截方式

第一種是常見的權限管理方式,第二種有時也可以通過第一種去進行實現,方法級的攔截容易實現,不過要以友好的方式顯示權限不足設計及實現就有些囉嗦。基於數據級的安全攔截實現上得更麻煩,在此不作介紹,我們只是針對第一種方式作設計。Spring Security在URL上已經提供了比較好的管理,不過其是以類似以下這種方式進行配置的。

 

Java代碼  收藏代碼
  1. <http auto-config='true'>  
  2.     <intercept-url pattern="/login.jsp*" filters="none"/>   
  3.     <intercept-url pattern="/**" access="ROLE_USER" />  
  4.     <form-login login-page='/login.jsp'/>  
  5. </http>  

 

這種要動態實現角色與權限的管理就顯得有些不足了,因此需要進行擴展實現,我們可以把一些不需要進行安全攔截的url放在Spring的以上配置中,設置filters=”none”,如images,css,js等,提高訪問的速度。


在擴展Spring Security之前,我們需要了解一下Spring Security的相關術語。

Authentication (認證)對象 
   其實就是一個可以通過Spring Security的認證的身份證明。如實現該接口的類UsernamePasswordAuthenticationToken,表示可以通過username及password作爲身份驗證。

 Authentication對象包含了

  •  Principal  標識是哪一個對象,可以認爲是用戶
  •    Credentials 信任的對象,如密碼。
  •  Authorities 權限的集合,在我們的系統中可以認爲是角色的集合 (authorities要賦予給principal的)


 SecurityContextHolder 
    是Spring Security的核心對象,是安全上下文的訪問的入口。如取得當前的登錄用戶可以從該類中的相應的方法取得。該類中包含ThreadLocal私有屬性用於存取SecurityContext,         SecurityContext包含Authentication私有屬性。如實現彈出窗口登錄功能的時候,輸入的用戶名及密碼並沒有最終經過SPRING SECURITY的filter,那麼如何使用得當前用戶可以成功登錄呢,其就是利用到這一點,通過該類拿到SecurityContext,然後設置一個認證的對象給它,SPRING SECURITY在看到該認證對象的時候,就會成功經過了身份的認證了。

其實也可以這樣理解,爲了處理Http請求間認證,Spring Security使用HttpSessionIntegrationFilter,HttpSessionIntegrationFilter用於在HttpSession存儲Http請求間的SecurityContext。不過我們可以通過SecurityContextHolder去拿到這個SecurityContext
AuthenticationManager 
    通過Providers 驗證 在當前 ContextHolder中的Authentication對象是否合法。 
AccessDecissionManager 
    經過投票機制來審批是否批准操作 
Interceptors(攔截器) 
    攔截器(如FilterSecurityInterceptor,JoinPoint,MethodSecurityInterceptor等)用於協調授權,認證等操作。

Spring Security是Spring中一個強大的安全管理框架,不過目前在我們系統中使用的僅是其中一部分的功能,則權限過濾安全檢查的功能。如果拋開這個框架,我們實現權限管理的時候,可能使用最多的方案還是使用Filter來進行過濾,在Filter裏判斷當前的用戶是否爲登錄用戶,若是登錄用戶,則看是否有權限訪問當前的資源,若爲未登錄用戶,則跳至登錄頁面。

 

二、擴展Spring Security

 

擴展Spring Security基於角色的管理策略,通過角色分配,保證系統的安全。其安全的手段包括以下:

1.    登錄時需要加上驗證碼
2.    所有的數據展示及訪問頁需要登錄後才能訪問
3.    用戶的數據庫密碼存儲時使用Sha-256的加密算法
4.    登錄後的所有系統的訪問URL均需要授權
5.    登錄多少次失敗後,可鎖定IP,約20分鐘後才能自動解鎖。(尚未實現)

權限設計目前是採用基於角色控制的方式,用戶需要訪問系統的資源,首先必須要授予一個角色,而該角色具有訪問系統資源的權限的能力,也可以認爲是權限的集合。因此,一個用戶要訪問系統的某個資源(如產品列表),則首先要授予一個能夠訪問產品列表資源的角色(如productAdmin)。只要任一個用戶擁有了該角色,即可以訪問該資源。
    
系統的安全涉及到兩個不同的概念,認證和授權。前者是關於確認用戶是否確實是他們所宣稱的身份。用戶進入系統的時候,首先要進行第一個操作就是進行身份認證,即Authentication。在系統中一般表現爲用戶用賬號跟密碼登錄。如果都正確了,則可以登錄系統。在現實中你可以這樣理解,員工在進入公司之前,需要進行身份的確認。身份確認通過後,則可以進入公司。進入公司後,並不代表可以隨便進入公司的每個辦公室。這時就需要每個看當前員工具有哪些角色,即授權。授權則是關於確認用戶是否有允許執行一個特定的操作。如當前員工是總經理,則可以進入總經理辦公室,並且可以進入普通員工的辦公區域。是因爲總經理已經授權可以出入這些地方。
在本系統中,權限表現爲功能菜單及系統訪問的URL。
    如:
        添加用戶,其訪問的url爲 /system/saveAppUser.do
        刪除用戶,其訪問的url爲/system/deleteAppUser.do
        查詢用戶,其訪問的url爲/system/listAppUser.do
因而用戶、角色、權限之間的關係可以用如下的圖描述:

 

Spring EXT 角色 權限

 

表設計


一個用戶可以有多個角色,每個角色有多個功能菜單,每個功能菜單會對應多個系統訪問的URL
表設計如下所示:
系統功能 權限設計

 

表說明: 
1.    app_user系統用戶表,放置系統的所有用戶
2.    user_role用戶角色,放置系統的所有角色
3.    app_role角色表,放置用戶角色
4.    role_fun角色對應的功能表,放置角色擁有的功能
5.    app_function系統的功能表,放置系統參與授權的所有功能
6.    fun_url系統的功能對應的權限URL表

目前我們需要擴展Spring Security的以下兩部分功能
1. 身份認證
2. 授權

Spring Security是由一組的filter來進行統一的過濾,不同的filter進行相應的權限過濾功能。不過在Security跟spring集成的過程中,其是由一個代理的類進行這些filter的統一管理。可以在web.xml中進行了查看,如下所示:

Java代碼  收藏代碼
  1. <filter>  
  2.       <filter-name>springSecurityFilterChain</filter-name>  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  3.     </filter>  
  4.    <filter-mapping>  
  5.       <filter-name>springSecurityFilterChain</filter-name>  
  6.       <url-pattern>*.do</url-pattern>  
  7.    </filter-mapping>  
  8.    <filter-mapping>  
  9.       <filter-name>springSecurityFilterChain</filter-name>  
  10.       <url-pattern>/index.jsp</url-pattern>  
  11.    </filter-mapping>  
  12.    <filter-mapping>  
  13.       <filter-name>springSecurityFilterChain</filter-name>  
  14.       <url-pattern>/file-upload</url-pattern>  
  15.    </filter-mapping>  

 

所有經過springSecurityFilterChain的url,都會轉到DelegatingFilterProxy類的bean去處理。而該Bean在Spring Security 2.0中,已經內置於安全管理的缺省的配置當中,我們只需要把app-security.xml加入我們系統管理中來即可。如下:

Java代碼  收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <b:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.              xmlns:b="http://www.springframework.org/schema/beans"  
  4.              xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  5.               http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">   
  6.     <http auto-config="true" access-denied-page="/403.jsp" lowercase-comparisons="true"   
  7.         access-decision-manager-ref="accessDecisionManager">  
  8.         <intercept-url pattern="/images/**" filters="none"/>  
  9.         <intercept-url pattern="/css/**" filters="none"/>  
  10.         <intercept-url pattern="/js/**" filters="none"/>  
  11.         <intercept-url pattern="/403*" filters="none"/>  
  12.         <intercept-url pattern="/404*" filters="none"/>  
  13.         <intercept-url pattern="/500*" filters="none"/>   
  14.         <intercept-url pattern="/ext3/**" filters="none"/>  
  15.         <intercept-url pattern="/fckeditor/**" filters="none"/>    
  16.         <intercept-url pattern="/jsonStruts**" filters="none"/>  
  17.         <form-login default-target-url="/index.jsp" login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" login-processing-url="/j_security_check" />  
  18.         <logout logout-url="/j_logout.do" logout-success-url="/login.jsp"/>   
  19.         <remember-me key="RememberAppUser"/>  
  20.     </http>  
  21.       
  22.      <b:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">  
  23.         <b:property name="allowIfAllAbstainDecisions" value="false"/>  
  24.         <b:property name="decisionVoters">  
  25.             <b:list>  
  26.                 <b:bean class="org.springframework.security.vote.RoleVoter">  
  27.                     <b:property name="rolePrefix" value="" />  
  28.                 </b:bean>  
  29.                 <b:bean class="org.springframework.security.vote.AuthenticatedVoter" />  
  30.             </b:list>  
  31.         </b:property>  
  32.     </b:bean>  
  33.   
  34.     <authentication-manager alias="authenticationManager"/>  
  35.           
  36.     <authentication-provider user-service-ref="appUserDao">  
  37.         <password-encoder hash="sha-256" base64="true"/>  
  38.     </authentication-provider>  
  39.   
  40.     <b:bean id="securityInterceptorFilter" class="com.htsoft.core.web.filter.SecurityInterceptorFilter" >  
  41.         <custom-filter after="FILTER_SECURITY_INTERCEPTOR" />  
  42.         <b:property name="securityDataSource" ref="securityDataSource"/>  
  43.     </b:bean>  
  44.       
  45.     <b:bean id="securityDataSource" class="com.htsoft.core.security.SecurityDataSource">  
  46.         <b:property name="appRoleService" ref="appRoleService"/>  
  47.         <b:property name="anonymousUrls">  
  48.             <b:set>  
  49.                 <b:value>/login.do</b:value>  
  50.                 <b:value>/check.do</b:value>  
  51.             </b:set>  
  52.         </b:property>  
  53.         <b:property name="publicUrls">  
  54.             <b:set>  
  55.                 <b:value>/modelsMenu.do</b:value>  
  56.                 <b:value>/itemsMenu.do</b:value>  
  57.                 <b:value>/file-upload</b:value>  
  58.                 <b:value>/index.jsp</b:value>  
  59.                   
  60.                 <b:value>/communicate/listPhoneBook.do</b:value>  
  61.                 <b:value>/communicate/listPhoneGroup.do</b:value>  
  62.                 <b:value>/communicate/moveMail.do</b:value>  
  63.                 <b:value>/communicate/listMailFolder.do</b:value>  
  64.                 <b:value>/communicate/removeMailFolder.do</b:value>  
  65.                 <b:value>/communicate/searchMail.do</b:value>  
  66.                   
  67.                 <b:value>/system/getAppUser.do</b:value>  
  68.                 <b:value>/system/checkDiary.do</b:value>  
  69.                 <b:value>/system/selectDepartment.do</b:value>  
  70.                 <b:value>/system/listAppRole.do</b:value>  
  71.             </b:set>  
  72.         </b:property>  
  73.     </b:bean>  
  74. </b:beans>  

 

身份認證

 

說明:當用戶登錄時,會根據用戶賬號及密碼進行驗證,驗證由authenticationManager來進,其會調用實現UserDetailsService接口實現類完成,在本系統,是由appUserDaoImpl類來實現。

而我們的用戶及角色實體要成爲安全框架識別的安全實體,需要相應實現不同的接口,如下所示:


訪問授權 

授權的管理是通過Filter來進行的,用戶訪問URL時,均需要經過Spring Security的URL進行授權。在本系統中,這個功能是通過SecurityInterceptorFilter來進行。

系統啓動時,會把所有的權限以[角色—URL列表]的形式放置在一個全局的Map中,用戶訪問系統的url時,就會根據當前用戶所擁有的角色是否包含此URL。這個全局的權限匹配源則由SecurityDataSource來提供。由於登錄用戶在進入系統後,都會具備一些常用的功能,所以每個用戶均有一個PUBLIC_ROLE的角色,代表可以訪問系統的公告資源。該角色對應的可訪問的URL,則配置在SecurityDataSource Bean中的publicUrls屬性中。

SecurityInterceptorFilter代碼如下所示:

Java代碼  收藏代碼
  1. package com.htsoft.core.web.filter;  
  2. /* 
  3.  *  廣州宏天軟件有限公司 OA辦公管理系統   -- http://www.jee-soft.cn 
  4.  *  Copyright (C) 2008-2009 GuangZhou HongTian Software Company 
  5. */  
  6. import java.io.IOException;  
  7. import java.util.HashMap;  
  8. import java.util.Set;  
  9. import javax.servlet.FilterChain;  
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import org.springframework.security.AccessDeniedException;  
  15. import org.springframework.security.Authentication;  
  16. import org.springframework.security.GrantedAuthority;  
  17. import org.springframework.security.context.SecurityContextHolder;  
  18. import org.springframework.web.filter.OncePerRequestFilter;  
  19.   
  20. import com.htsoft.core.security.SecurityDataSource;  
  21. /** 
  22.  * 權限攔載器 
  23.  * @author csx 
  24.  */  
  25. public class SecurityInterceptorFilter extends OncePerRequestFilter {  
  26.       
  27.     /** 
  28.      * 角色權限映射列表源,用於權限的匹配 
  29.      */  
  30.     private HashMap<String, Set<String>> roleUrlsMap=null;  
  31.       
  32.     private SecurityDataSource securityDataSource;  
  33.   
  34.     public void setSecurityDataSource(SecurityDataSource securityDataSource) {  
  35.         this.securityDataSource = securityDataSource;  
  36.     }  
  37.   
  38.     @Override  
  39.     protected void doFilterInternal(HttpServletRequest request,  
  40.             HttpServletResponse response, FilterChain chain) throws ServletException, IOException {  
  41.         if(logger.isDebugEnabled()){  
  42.             logger.debug("...enter the SecurityInterceptorFilter doFilterInternal here...");  
  43.         }  
  44.         String url=request.getRequestURI();  
  45.         //若有contextPath,則切出來  
  46.         if(org.springframework.util.StringUtils.hasLength(request.getContextPath())){  
  47.             String contextPath=request.getContextPath();  
  48.             int index=url.indexOf(contextPath);  
  49.             if(index!=-1){  
  50.                 url=url.substring(index+contextPath.length());  
  51.             }  
  52.         }  
  53.           
  54.         Authentication auth= SecurityContextHolder.getContext().getAuthentication();//取得認證器  
  55.           
  56.         boolean isSuperUser=false;  
  57.         for(int i=0;i<auth.getAuthorities().length;i++){  
  58.             //logger.info("角色名稱:"+auth.getAuthorities()[i].getAuthority());  
  59.             if("超級管理員".equals(auth.getAuthorities()[i].getAuthority())){  
  60.                 isSuperUser=true;  
  61.             }  
  62.         }  
  63.         if(!isSuperUser){//非超級管理員  
  64.             if(!isUrlGrantedRight(url,auth)){//如果未授權  
  65.                 logger.info("ungranted url:" + url);  
  66.                 throw new AccessDeniedException("Access is denied! Url:" + url + " User:" + SecurityContextHolder.getContext().getAuthentication().getName());  
  67.             }  
  68.         }  
  69.         if(logger.isInfoEnabled()){  
  70.             logger.info("pass the url:" + url);  
  71.         }  
  72.         //進行下一個Filter  
  73.         chain.doFilter(request, response);  
  74.     }  
  75.       
  76.     /** 
  77.      * 檢查該URL是否授權訪問 
  78.      * @param url 
  79.      * @return 
  80.      */  
  81.     private boolean isUrlGrantedRight(String url,Authentication auth){  
  82.           
  83.         //遍歷該用戶下所有角色對應的URL,看是否有匹配的  
  84.         for(GrantedAuthority ga:auth.getAuthorities()){  
  85.             Set<String> urlSet=roleUrlsMap.get(ga.getAuthority());  
  86.             //TODO AntPathMatcher here  
  87.             if(urlSet!=null && urlSet.contains(url)){  
  88.                 return true;  
  89.             }  
  90.         }  
  91.         return false;  
  92.     }  
  93.       
  94.     public void loadDataSource(){  
  95.         roleUrlsMap=securityDataSource.getDataSource();  
  96.     }  
  97.       
  98.     @Override  
  99.     public void afterPropertiesSet() throws ServletException {  
  100.         loadDataSource();  
  101.         if(roleUrlsMap==null){  
  102.             throw new RuntimeException("沒有進行設置系統的權限匹配數據源");  
  103.         }  
  104.     }  
  105. }  

 三、EXT的擴展實現 

至此,我們完成了對Spring Security的權限擴展,但是EXT訪問的時候,我們的應用程序都是在一個頁面上進行,也就是我們之前說的One Application One Page,幾乎所有的請求都是通過Ajax的請求來時行,頁面沒有刷新,當權限不足的時候,我們如何提示用戶呢?另外我們的功能菜單又是如何來根據用戶的角色來顯示出來呢?在此,我們把需要把角色、功能、權限URL需要進行統一管理。我們從以下幾個方面來進行擴展。


當用戶權限不足時,我們需要提示用戶無限訪問該URL,在app-sercurity.xml中,我們配置了以下:

Java代碼  收藏代碼
  1. <http auto-config="true" access-denied-page="/403.jsp" lowercase-comparisons="true"   
  2.         access-decision-manager-ref="accessDecisionManager">  
  3.         <intercept-url pattern="/images/**" filters="none"/>  
  4.         <intercept-url pattern="/css/**" filters="none"/>  
  5.         <intercept-url pattern="/js/**" filters="none"/>  
  6.         <intercept-url pattern="/403*" filters="none"/>  
  7.         <intercept-url pattern="/404*" filters="none"/>  
  8.         <intercept-url pattern="/500*" filters="none"/>   
  9.         <intercept-url pattern="/ext3/**" filters="none"/>  
  10.         <intercept-url pattern="/fckeditor/**" filters="none"/>    
  11.         <intercept-url pattern="/jsonStruts**" filters="none"/>  
  12.         <form-login default-target-url="/index.jsp" login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" login-processing-url="/j_security_check" />  
  13.         <logout logout-url="/j_logout.do" logout-success-url="/login.jsp"/>   
  14.         <remember-me key="RememberAppUser"/>  
  15.     </http>  

 

即當用戶權限不足時,會跳至403頁,因此我們可以在此上作文章,當跳至403頁時,我們往response的頭寫一個標識,在ext的connection中獲取返回結果時,我們根據這個標識來給用戶提示一個友好的信息,如:

 

403.jsp的代碼實現:

 

Java代碼  收藏代碼
  1. <%@ page pageEncoding="UTF-8"%><%   
  2.  response.addHeader("__forbidden","true");  
  3.  String basePath=request.getContextPath();  
  4. %>  
  5. <html>  
  6.  <head>  
  7.   <title>訪問拒絕</title>  
  8.    <style type="text/css">  
  9.    <!--  
  10.    .STYLE10 {  
  11.     font-family: "黑體";  
  12.     font-size: 36px;  
  13.    }  
  14.    -->    
  15.    </style>  
  16.  </head>  
  17.  <body>  
  18.   <table width="510" border="0" align="center" cellpadding="0" cellspacing="0">  
  19.    <tr>  
  20.      <td><img src="<%=basePath%>/images/error_top.jpg" width="510" height="80" /></td>  
  21.      </tr>  
  22.    <tr>  
  23.      <td height="200" align="center" valign="top" background="<%=basePath%>/images/error_bg.jpg">  
  24.       <table width="80%" border="0" cellspacing="0" cellpadding="0">  
  25.          <tr>  
  26.            <td width="34%" align="right"><img src="<%=basePath%>/images/error.gif" width="128" height="128"></td>  
  27.            <td width="66%" valign="bottom" align="center">  
  28.             <span class="STYLE10">訪問被拒絕</span>  
  29.             <div style="text-align: left;line-height: 22px;">  
  30.              <font size="2">對不起,您的當前角色沒有查看此頁面的權限。請聯繫您的系統管理員,以獲得相應的權限。點擊這裏返回主頁。如果需要技術支持,點擊這裏發送郵件。</font>  
  31.           </div>  
  32.           <a href="#" onclick="javascript:document.location.href='<%=basePath%>/j_logout.do';">重 新 登 錄</a>   
  33.           <a href="#" onclick="javascript:history.back(-1);">後 退</a>  
  34.         </td>  
  35.        </table>  
  36.        </td>  
  37.    </tr>        
  38.    <tr>  
  39.      <td><img src="<%=basePath%>/images/error_bootom.jpg" width="510" height="32" /></td>  
  40.       </tr>  
  41.  </table>  
  42.  </body>  
  43. </html>  

 處理該標識:

 

Java代碼  收藏代碼
  1. App.init = function() {  
  2.     Ext.util.Observable.observeClass(Ext.data.Connection);  
  3.     Ext.data.Connection.on('requestcomplete', function(conn, resp,options ){  
  4.         if (resp && resp.getResponseHeader){  
  5.             if(resp.getResponseHeader('__timeout')) {  
  6.                 Ext.ux.Toast.msg('操作提示:','操作已經超時,請重新登錄!');  
  7.                 window.location.href=__ctxPath+'/index.jsp?randId=' + parseInt(1000*Math.random());  
  8.             }  
  9.             if(resp.getResponseHeader('__forbidden')){  
  10.                 Ext.ux.Toast.msg('系統訪問權限提示:','你目前沒有權限訪問:{0}',options.url);  
  11.             }  
  12.         }  
  13.     });  
  14. …  
  15. }  

 

Connection的這個requestcomplete事件是所有的Ajax請求都必須觸發的,所以把它作爲總的入口。
另外,用戶登錄後,其功能的菜單如何來配置呢,因此應用程序是通過一個全局的menu.xml文件來進行功能菜單的管理,同時也包括其功能與URL的配置。

Java代碼  收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <Menus>  
  3.     <Items id="SystemSetting" text="系統設置" iconCls="menu-system">  
  4.         ...  
  5.         <Item id="AppRoleView" iconCls="menu-role" text="角色設置">  
  6.             <Function id="_AppRoleList" text="查看角色" iconCls="menu-list">  
  7.                 <url>/system/listAppRole.do</url>  
  8.             </Function>  
  9.             <Function id="_AppRoleAdd" text="添加角色" iconCls="menu-add">  
  10.                 <url>/system/listAppRole.do</url>  
  11.                 <url>/system/saveAppRole.do</url>  
  12.             </Function>  
  13.             <Function id="_AppRoleEdit" text="編輯角色" iconCls="menu-add">  
  14.                 <url>/system/listAppRole.do</url>  
  15.                 <url>/system/saveAppRole.do</url>  
  16.             </Function>  
  17.             <Function id="_AppRoleDel" text="刪除角色" iconCls="menu-del">  
  18.                 <url>/system/listAppRole.do</url>  
  19.                 <url>/system/mulDelAppRole.do</url>  
  20.             </Function>  
  21.             <Function id="_AppRoleGrant" text="授權角色">  
  22.                 <url>/system/listAppRole.do</url>  
  23.                 <url>/system/grantAppRole.do</url>  
  24.             </Function>  
  25.         </Item>  
  26.         ...  
  27.         <Item id="ReportTemplateView" iconCls="menu-report" text="報表管理">  
  28.             ...  
  29.         </Item>  
  30.     </Items>  
  31. </Menus>  

 

這個XML文件會在應用程序啓動添加至系統的全局變量中,以“角色”對應“URL”的Map提供數據源來進行。

那麼角色對應的URL是如何來構造的,這個相對簡單一些,以上的功能及菜單,其均存在一個Id,如角色設置(AppRoleView),添加角色“_AppRoleAdd”。
每個角色就保存這些ID,所以加載這些ID,就有辦法把其下的URL全部加載出來,從而形成角色與URL的映射關係。

另外,我們還可以把用戶所擁有的權限,通過該用戶擁有哪些角色,每個角色包括哪些權限的ID,從而構造出該用戶的權限集合。如下所示,當用戶登錄後,我們把所有的ID集中放在用戶的rights字段中,這樣就可以通過ID來決定用戶是否有權限訪問某個功能按鈕,從而達到功能級別的控制,如:

 

Java代碼  收藏代碼
  1. //加載權限  
  2.     Ext.Ajax.request({  
  3.             url:__ctxPath+'/system/getCurrentAppUser.do',  
  4.             method:'Get',  
  5.             success:function(response,options){  
  6.                 var object=Ext.util.JSON.decode(response.responseText);  
  7.                 //取得當前登錄用戶的相關信息,包括權限  
  8.                 curUserInfo=new UserInfo(object.user.userId,object.user.fullname,object.user.rights);  
  9.             }  
  10.     });  

 以下爲user.rights的構造,是在用戶登錄的時候進行配置實現,爲AppUserDaoImpl.java的部分代碼

 

Java代碼  收藏代碼
  1. public UserDetails loadUserByUsername(final String username)  
  2.             throws UsernameNotFoundException, DataAccessException {  
  3.         return (UserDetails) getHibernateTemplate().execute(  
  4.                 new HibernateCallback() {  
  5.                     public Object doInHibernate(Session session)  
  6.                             throws HibernateException, SQLException {  
  7.                         String hql = "from AppUser ap where ap.username=? and ap.delFlag = ?";  
  8.                         Query query = session.createQuery(hql);  
  9.                         query.setString(0, username);  
  10.                         query.setShort(1, Constants.FLAG_UNDELETED);  
  11.                         AppUser user = null;  
  12.                         try {  
  13.                             user = (AppUser) query.uniqueResult();  
  14.                             if (user != null) {  
  15.                                 Hibernate.initialize(user.getRoles());  
  16.                                 Hibernate.initialize(user.getDepartment());  
  17.                                   
  18.                                 //進行合併權限的處理  
  19.                                 Set<AppRole> roleSet=user.getRoles();  
  20.                                 Iterator<AppRole> it=roleSet.iterator();  
  21.                                   
  22.                                 while(it.hasNext()){  
  23.                                     AppRole role=it.next();  
  24.                                     if(role.getRoleId().equals(AppRole.SUPER_ROLEID)){//具有超級權限  
  25.                                         user.getRights().clear();  
  26.                                         user.getRights().add(AppRole.SUPER_RIGHTS);  
  27.                                         break;  
  28.                                     }else{  
  29.                                         if(StringUtils.isNotEmpty(role.getRights())){  
  30.                                             String[]items=role.getRights().split("[,]");  
  31.                                             for(int i=0;i<items.length;i++){  
  32.                                                 if(!user.getRights().contains(items[i])){  
  33.                                                     user.getRights().add(items[i]);  
  34.                                                 }  
  35.                                             }  
  36.                                         }  
  37.                                     }  
  38.                                 }  
  39.                                   
  40.                             }  
  41.                         } catch (Exception ex) {  
  42.                             logger.warn("user:" + username  
  43.                                     + " can't not loding rights:"  
  44.                                     + ex.getMessage());  
  45.                         }  
  46.                         return user;  
  47.                     }  
  48.                 });  
  49.     }  

 

而其最終的實現效果可以參見我另一篇博客:

http://man1900.iteye.com/blog/517248

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