<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    CONAN ZONE

    你越掙扎我就越興奮

    BlogJava 首頁 新隨筆 聯(lián)系 聚合 管理
      0 Posts :: 282 Stories :: 0 Comments :: 0 Trackbacks
    搭建基礎(chǔ)環(huán)境

    首先我們?yōu)槭纠罱ɑ镜拈_發(fā)環(huán)境,環(huán)境的搭建方式,可以參考我的另外一篇文章:http://www.javaeye.com/wiki/struts2/1321-struts2-development-environment-to-build

    整個(gè)環(huán)境的搭建包括:創(chuàng)建合適的目錄結(jié)構(gòu)、加入了合適的Library,加入了基本的Jetty啟動(dòng)類、加入基本的配置文件等。最終的項(xiàng)目結(jié)構(gòu),可以參考我的附件。

    參考文檔

    這里主要的參考文檔是Spring Security的自帶的Reference。網(wǎng)絡(luò)上有一個(gè)它的中文翻譯,地址如下:http://www.family168.com/tutorial/springsecurity/html/springsecurity.html

    除此之外,springside有一個(gè)比較完整的例子,不過是基于Acegi的,我也參閱了其中的一些實(shí)現(xiàn)。

    Spring Security基本配置

    Spring Security是基于Spring的的權(quán)限認(rèn)證框架,對于Spring和Acegi已經(jīng)比較熟悉的同學(xué)對于之前的配置方式應(yīng)該已經(jīng)非常了解。接下來的例子,將向大家展示Spring Security基于schema的配置方式。

    最小化配置

    1. 在web.xml文件中加入Filter聲明

    Xml代碼 復(fù)制代碼
    1. <!-- Spring security Filter -->  
    2. <filter>  
    3.     <filter-name>springSecurityFilterChain</filter-name>  
    4.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
    5. </filter>  
    6. <filter-mapping>  
    7.     <filter-name>springSecurityFilterChain</filter-name>  
    8.     <url-pattern>/*</url-pattern>  
    9. </filter-mapping>  


    這個(gè)Filter會(huì)攔截所有的URL請求,并且對這些URL請求進(jìn)行Spring Security的驗(yàn)證。

    注意,springSecurityFilterChain這個(gè)名稱是由命名空間默認(rèn)創(chuàng)建的用于處理web安全的一個(gè)內(nèi)部的bean的id。所以你在你的Spring配置文件中,不應(yīng)該再使用這個(gè)id作為你的bean。

    與Acegi的配置不同,Acegi需要自行聲明一個(gè)Spring的bean來作為Filter的實(shí)現(xiàn),而使用Spring Security后,無需再額外定義bean,而是使用<http>元素進(jìn)行配置。

    2. 使用最小的<http>配置

    Xml代碼 復(fù)制代碼
    1. <http auto-config='true'>  
    2.     <intercept-url pattern="/**" access="ROLE_USER" />  
    3. </http>  


    這段配置表示:我們要保護(hù)應(yīng)用程序中的所有URL,只有擁有ROLE_USER角色的用戶才能訪問。你可以使用多個(gè)<intercept-url>元素為不同URL的集合定義不同的訪問需求,它們會(huì)被歸入一個(gè)有序隊(duì)列中,每次取出最先匹配的一個(gè)元素使用。 所以你必須把期望使用的匹配條件放到最上邊。

    3. 配置UserDetailsService來指定用戶和權(quán)限

    接下來,我們來配置一個(gè)UserDetailsService來指定用戶和權(quán)限:

    Xml代碼 復(fù)制代碼
    1. <authentication-provider>  
    2.     <user-service>  
    3.       <user name="downpour" password="downpour" authorities="ROLE_USER, ROLE_ADMIN" />  
    4.       <user name="robbin" password="robbin" authorities="ROLE_USER" />  
    5.       <user name="QuakeWang" password="QuakeWang" authorities="ROLE_ADMIN" />  
    6.     </user-service>  
    7.   </authentication-provider>  


    在這里,downpour擁有ROLE_USER和ROLE_ADMIN的權(quán)限,robbin擁有ROLE_USER權(quán)限,QuakeWang擁有ROLE_ADMIN的權(quán)限

    4. 小結(jié)

    有了以上的配置,你已經(jīng)可以跑簡單的Spring Security的應(yīng)用了。只不過在這里,我們還缺乏很多基本的元素,所以我們尚不能對上面的代碼進(jìn)行完整性測試。

    如果你具備Acegi的知識(shí),你會(huì)發(fā)現(xiàn),有很多Acegi中的元素,在Spring Security中都沒有了,這些元素包括:表單和基本登錄選項(xiàng)、密碼編碼器、Remember-Me認(rèn)證等等。

    接下來,我們就來詳細(xì)剖析一下Spring Security中的這些基本元素。

    剖析基本配置元素

    1. 有關(guān)auto-config屬性

    在上面用到的auto-config屬性,其實(shí)是下面這些配置的縮寫:

    Xml代碼 復(fù)制代碼
    1. <http>  
    2.     <intercept-url pattern="/**" access="ROLE_USER" />  
    3.     <form-login />  
    4.     <anonymous />  
    5.     <http-basic />  
    6.     <logout />  
    7.     <remember-me />  
    8. </http>  


    這些元素分別與登錄認(rèn)證,匿名認(rèn)證,基本認(rèn)證,注銷處理和remember-me對應(yīng)。 他們擁有各自的屬性,可以改變他們的具體行為。

    這樣,我們在Acegi中所熟悉的元素又浮現(xiàn)在我們的面前。只是在這里,我們使用的是命名空間而已。

    2. 與Acegi的比較

    我們仔細(xì)觀察一下沒有auto-config的那段XML配置,是不是熟悉多了?讓我們來將基于命名空間的配置與傳統(tǒng)的Acegi的bean的配置做一個(gè)比較,我們會(huì)發(fā)現(xiàn)以下的區(qū)別:

    1) 基于命名空間的配置更加簡潔,可維護(hù)性更強(qiáng)

    例如,基于命名空間進(jìn)行登錄認(rèn)證的配置代碼,可能像這樣:

    Xml代碼 復(fù)制代碼
    1. <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/work" />  


    如果使用老的Acegi的Bean的定義方式,可能像這樣:

    Xml代碼 復(fù)制代碼
    1. <bean id="authenticationProcessingFilter"  
    2.           class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter">  
    3.     <property name="authenticationManager"  
    4.                   ref="authenticationManager"/>  
    5.     <property name="authenticationFailureUrl"  
    6.                   value="/login.jsp?error=1"/>  
    7.     <property name="defaultTargetUrl" value="/work"/>  
    8.     <property name="filterProcessesUrl"  
    9.                   value="/j_acegi_security_check"/>  
    10.     <property name="rememberMeServices" ref="rememberMeServices"/>  
    11. </bean>  


    這樣的例子很多,有興趣的讀者可以一一進(jìn)行比較。

    2) 基于命名空間的配置,我們無需再擔(dān)心由于過濾器鏈的順序而導(dǎo)致的錯(cuò)誤

    以前,Acegi在缺乏默認(rèn)內(nèi)置配置的情況下,你需要自己來定義所有的bean,并指定這些bean在過濾器鏈中的順序。一旦順序錯(cuò)了,很容易發(fā)生錯(cuò)誤。而現(xiàn)在,過濾器鏈的順序被默認(rèn)指定,你不需要在擔(dān)心由于順序的錯(cuò)誤而導(dǎo)致的錯(cuò)誤。

    3. 過濾器鏈在哪里

    到目前為止,我們都還沒有討論過整個(gè)Spring Security的核心部分:過濾器鏈。在原本Acegi的配置中,我們大概是這樣配置我們的過濾器鏈的:

    Xml代碼 復(fù)制代碼
    1. <bean id="filterChainProxy"  
    2.           class="org.acegisecurity.util.FilterChainProxy">  
    3.     <property name="filterInvocationDefinitionSource">  
    4.         <value>  
    5.                 CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON   
    6.                 PATTERN_TYPE_APACHE_ANT                    
    7.                 /common/**=#NONE#    
    8.                 /css/**=#NONE#    
    9.                 /images/**=#NONE#   
    10.                 /js/**=#NONE#    
    11.                 /login.jsp=#NONE#   
    12.                 /**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,exceptionTranslationFilter,filterSecurityInterceptor   
    13.         </value>  
    14.     </property>  
    15. </bean>  


    其中,每個(gè)過濾器鏈都將對應(yīng)于Spring配置文件中的bean的id。

    現(xiàn)在,在Spring Security中,我們將看不到這些配置,這些配置都被內(nèi)置在<http>節(jié)點(diǎn)中。讓我們來看看這些默認(rèn)的,已經(jīng)被內(nèi)置的過濾器:


    這些過濾器已經(jīng)被Spring容器默認(rèn)內(nèi)置注冊,這也就是我們不再需要在配置文件中定義那么多bean的原因。

    同時(shí),過濾器順序在使用命名空間的時(shí)候是被嚴(yán)格執(zhí)行的。它們在初始化的時(shí)候就預(yù)先被排好序。不僅如此,Spring Security規(guī)定,你不能替換那些<http>元素自己使用而創(chuàng)建出的過濾器,比如HttpSessionContextIntegrationFilter, ExceptionTranslationFilter 或 FilterSecurityInterceptor

    當(dāng)然,這樣的規(guī)定是否合理,有待進(jìn)一步討論。因?yàn)閷?shí)際上在很多時(shí)候,我們希望覆蓋過濾器鏈中的某個(gè)過濾器的默認(rèn)行為。而Spring Security的這種規(guī)定在一定程度上限制了我們的行為。

    不過Spring Security允許你把你自己的過濾器添加到隊(duì)列中,使用custom-filter元素,并且指定你的過濾器應(yīng)該出現(xiàn)的位置:

    Xml代碼 復(fù)制代碼
    1. <beans:bean id="myFilter" class="com.mycompany.MySpecialAuthenticationFilter">  
    2.     <custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/>  
    3. </beans:bean>  


    不僅如此,你還可以使用after或before屬性,如果你想把你的過濾器添加到隊(duì)列中另一個(gè)過濾器的前面或后面。 可以分別在position屬性使用"FIRST"或"LAST"來指定你想讓你的過濾器出現(xiàn)在隊(duì)列元素的前面或后面。

    這個(gè)特性或許能夠在一定程度上彌補(bǔ)Spring Security的死板規(guī)定,而在之后的應(yīng)用中,我也會(huì)把它作為切入點(diǎn),對資源進(jìn)行管理。

    另外,我需要補(bǔ)充一點(diǎn)的是,對于在http/intercept-url中沒有進(jìn)行定義的URL,將會(huì)默認(rèn)使用系統(tǒng)內(nèi)置的過濾器鏈進(jìn)行權(quán)限認(rèn)證。所以,你并不需要在http/intercept-url中額外定義一個(gè)類似/**的匹配規(guī)則。

    使用數(shù)據(jù)庫對用戶和權(quán)限進(jìn)行管理

    一般來說,我們都有使用數(shù)據(jù)庫對用戶和權(quán)限進(jìn)行管理的需求,而不會(huì)把用戶寫死在配置文件里。所以,我們接下來就重點(diǎn)討論使用數(shù)據(jù)庫對用戶和權(quán)限進(jìn)行管理的方法。

    用戶和權(quán)限的關(guān)系設(shè)計(jì)

    在此之前,我們首先需要討論一下用戶(User)和權(quán)限(Role)之間的關(guān)系。Spring Security在默認(rèn)情況下,把這兩者當(dāng)作一對多的關(guān)系進(jìn)行處理。所以,在Spring Security中對這兩個(gè)對象所采用的表結(jié)構(gòu)關(guān)系大概像這樣:

    Java代碼 復(fù)制代碼
    1. CREATE TABLE users (   
    2.   username VARCHAR(50) NOT NULL PRIMARY KEY,   
    3.   password VARCHAR(50) NOT NULL,   
    4.   enabled BIT NOT NULL   
    5. );   
    6.   
    7. CREATE TABLE authorities (   
    8.   username VARCHAR(50) NOT NULL,   
    9.   authority VARCHAR(50) NOT NULL   
    10. );  


    不過這種設(shè)計(jì)方式在實(shí)際生產(chǎn)環(huán)境中基本上不會(huì)采用。一般來說,我們會(huì)使用邏輯主鍵ID來標(biāo)示每個(gè)User和每個(gè)Authorities(Role)。而且從典型意義上講,他們之間是一個(gè)多對多的關(guān)系,我們會(huì)采用3張表來表示,下面是我在MySQL中建立的3張表的schema示例:
    Java代碼 復(fù)制代碼
    1. CREATE TABLE `user` (   
    2.   `id` int(11) NOT NULL auto_increment,   
    3.   `name` varchar(255default NULL,   
    4.   `password` varchar(255default NULL,   
    5.   `disabled` int(1) NOT NULL,   
    6.   PRIMARY KEY  (`id`)   
    7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;   
    8.   
    9. CREATE TABLE `role` (   
    10.   `id` int(11) NOT NULL auto_increment,   
    11.   `name` varchar(255default NULL,   
    12.   PRIMARY KEY  (`id`)   
    13. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;   
    14.   
    15. CREATE TABLE `user_role` (   
    16.   `user_id` int(11) NOT NULL,   
    17.   `role_id` int(11) NOT NULL,   
    18.   PRIMARY KEY  (`user_id`,`role_id`),   
    19.   UNIQUE KEY `role_id` (`role_id`),   
    20.   KEY `FK143BF46AF6AD4381` (`user_id`),   
    21.   KEY `FK143BF46A51827FA1` (`role_id`),   
    22.   CONSTRAINT `FK143BF46A51827FA1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`),   
    23.   CONSTRAINT `FK143BF46AF6AD4381` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)   
    24. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  


    通過配置SQL來模擬用戶和權(quán)限

    有了數(shù)據(jù)庫的表設(shè)計(jì),我們就可以在Spring Security中,通過配置SQL,來模擬用戶和權(quán)限,這依然通過<authentication-provider>來完成:

    Xml代碼 復(fù)制代碼
    1. <authentication-provider>  
    2.     <jdbc-user-service data-source-ref="dataSource"  
    3.     users-by-username-query="SELECT U.username, U.password, U.accountEnabled AS 'enabled' FROM User U where U.username=?"  
    4.     authorities-by-username-query="SELECT U.username, R.name as 'authority' FROM User U JOIN Authority A ON u.id = A.userId JOIN Role R ON R.id = A.roleId WHERE U.username=?"/>  
    5. </authentication-provider>  


    這里給出的是一個(gè)使用SQL進(jìn)行模擬用戶和權(quán)限的示例。其中你需要為運(yùn)行SQL準(zhǔn)備相應(yīng)的dataSource。這個(gè)dataSource應(yīng)該對應(yīng)于Spring中的某個(gè)bean的定義。

    從這段配置模擬用戶和權(quán)限的情況來看,實(shí)際上Spring Security對于用戶,需要username,password,accountEnabled三個(gè)字段。對于權(quán)限,它需要的是username和authority2個(gè)字段。

    也就是說,如果我們能夠通過其他的方式,模擬上面的這些對象,并插入到Spring Security中去,我們同樣能夠?qū)崿F(xiàn)用戶和權(quán)限的認(rèn)證。接下來,我們就來看看我們?nèi)绾瓮ㄟ^自己的實(shí)現(xiàn),來完成這件事情。

    通過擴(kuò)展Spring Security的默認(rèn)實(shí)現(xiàn)來進(jìn)行用戶和權(quán)限的管理

    事實(shí)上,Spring Security提供了2個(gè)認(rèn)證的接口,分別用于模擬用戶和權(quán)限,以及讀取用戶和權(quán)限的操作方法。這兩個(gè)接口分別是:UserDetails和UserDetailsService。

    Java代碼 復(fù)制代碼
    1. public interface UserDetails extends Serializable {   
    2.        
    3.     GrantedAuthority[] getAuthorities();   
    4.   
    5.     String getPassword();   
    6.   
    7.     String getUsername();   
    8.   
    9.     boolean isAccountNonExpired();   
    10.   
    11.     boolean isAccountNonLocked();   
    12.   
    13.     boolean isCredentialsNonExpired();   
    14.   
    15.     boolean isEnabled();   
    16. }  


    Java代碼 復(fù)制代碼
    1. public interface UserDetailsService {   
    2.     UserDetails loadUserByUsername(String username)   
    3.         throws UsernameNotFoundException, DataAccessException;   
    4. }  


    非常清楚,一個(gè)接口用于模擬用戶,另外一個(gè)用于模擬讀取用戶的過程。所以我們可以通過實(shí)現(xiàn)這兩個(gè)接口,來完成使用數(shù)據(jù)庫對用戶和權(quán)限進(jìn)行管理的需求。在這里,我將給出一個(gè)使用Hibernate來定義用戶和權(quán)限之間關(guān)系的示例。

    1. 定義User類和Role類,使他們之間形成多對多的關(guān)系
    Java代碼 復(fù)制代碼
    1. @Entity  
    2. @Proxy(lazy = false)   
    3. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    4. public class User {   
    5.        
    6.     private static final long serialVersionUID = 8026813053768023527L;   
    7.   
    8.     @Id  
    9.     @GeneratedValue  
    10.     private Integer id;   
    11.        
    12.     private String name;   
    13.        
    14.     private String password;   
    15.        
    16.     private boolean disabled;   
    17.        
    18.     @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)   
    19.     @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))   
    20.     @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    21.     private Set<Role> roles;   
    22.   
    23.         // setters and getters   
    24. }  


    Java代碼 復(fù)制代碼
    1. @Entity  
    2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    3. public class Role {   
    4.        
    5.     @Id  
    6.     @GeneratedValue  
    7.     private Integer id;   
    8.        
    9.     private String name;   
    10.            
    11.         // setters and getters   
    12. }  


    請注意這里的Annotation的寫法。同時(shí),我為User和Role之間配置了緩存。并且將他們之間的關(guān)聯(lián)關(guān)系設(shè)置的lazy屬性設(shè)置成false,從而保證在User對象取出之后的使用不會(huì)因?yàn)槊撾xsession的生命周期而產(chǎn)生lazy loading問題。

    2. 使User類實(shí)現(xiàn)UserDetails接口

    接下來,我們讓User類去實(shí)現(xiàn)UserDetails接口:

    Java代碼 復(fù)制代碼
    1. @Entity  
    2. @Proxy(lazy = false)   
    3. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    4. public class User implements UserDetails {   
    5.        
    6.     private static final long serialVersionUID = 8026813053768023527L;   
    7.   
    8.     @Id  
    9.     @GeneratedValue  
    10.     private Integer id;   
    11.        
    12.     private String name;   
    13.        
    14.     private String password;   
    15.        
    16.     private boolean disabled;   
    17.        
    18.     @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)   
    19.     @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))   
    20.     @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    21.     private Set<Role> roles;   
    22.        
    23.     /**  
    24.      * The default constructor  
    25.      */  
    26.     public User() {   
    27.            
    28.     }   
    29.   
    30.     /* (non-Javadoc)  
    31.      * @see org.springframework.security.userdetails.UserDetails#getAuthorities()  
    32.      */  
    33.     public GrantedAuthority[] getAuthorities() {   
    34.         List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());   
    35.         for(Role role : roles) {   
    36.             grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));   
    37.         }   
    38.         return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);   
    39.     }   
    40.   
    41.     /* (non-Javadoc)  
    42.      * @see org.springframework.security.userdetails.UserDetails#getPassword()  
    43.      */  
    44.     public String getPassword() {   
    45.         return password;   
    46.     }   
    47.   
    48.     /* (non-Javadoc)  
    49.      * @see org.springframework.security.userdetails.UserDetails#getUsername()  
    50.      */  
    51.     public String getUsername() {   
    52.         return name;   
    53.     }   
    54.   
    55.     /* (non-Javadoc)  
    56.      * @see org.springframework.security.userdetails.UserDetails#isAccountNonExpired()  
    57.      */  
    58.     public boolean isAccountNonExpired() {   
    59.         return true;   
    60.     }   
    61.   
    62.     /* (non-Javadoc)  
    63.      * @see org.springframework.security.userdetails.UserDetails#isAccountNonLocked()  
    64.      */  
    65.     public boolean isAccountNonLocked() {   
    66.         return true;   
    67.     }   
    68.   
    69.     /* (non-Javadoc)  
    70.      * @see org.springframework.security.userdetails.UserDetails#isCredentialsNonExpired()  
    71.      */  
    72.     public boolean isCredentialsNonExpired() {   
    73.         return true;   
    74.     }   
    75.   
    76.     /* (non-Javadoc)  
    77.      * @see org.springframework.security.userdetails.UserDetails#isEnabled()  
    78.      */  
    79.     public boolean isEnabled() {   
    80.         return !this.disabled;   
    81.     }   
    82.          
    83.       // setters and getters   
    84. }  


    實(shí)現(xiàn)UserDetails接口中的每個(gè)函數(shù),其實(shí)沒什么很大的難度,除了其中的一個(gè)函數(shù)我需要額外強(qiáng)調(diào)一下:

    Java代碼 復(fù)制代碼
    1. /* (non-Javadoc)  
    2.  * @see org.springframework.security.userdetails.UserDetails#getAuthorities()  
    3.  */  
    4. public GrantedAuthority[] getAuthorities() {   
    5.     List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());   
    6.     for(Role role : roles) {   
    7.         grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));   
    8.         }   
    9.         return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);   
    10. }  


    這個(gè)函數(shù)的實(shí)際作用是根據(jù)User返回這個(gè)User所擁有的權(quán)限列表。如果以上面曾經(jīng)用過的例子來說,如果當(dāng)前User是downpour,我需要得到ROLE_USER和ROLE_ADMIN;如果當(dāng)前User是robbin,我需要得到ROLE_USER。

    了解了含義,實(shí)現(xiàn)就變得簡單了,由于User與Role是多對多的關(guān)系,我們可以通過User得到所有這個(gè)User所對應(yīng)的Role,并把這些Role的name拼裝起來返回。

    由此可見,實(shí)現(xiàn)UserDetails接口,并沒有什么神秘的地方,它只是實(shí)際上在一定程度上只是代替了使用配置文件的硬編碼:

    Xml代碼 復(fù)制代碼
    1. <user name="downpour" password="downpour" authorities="ROLE_USER, ROLE_ADMIN" />  


    3. 實(shí)現(xiàn)UserDetailsService接口

    Java代碼 復(fù)制代碼
    1. @Repository("securityManager")   
    2. public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService {   
    3.   
    4.     /**  
    5.      * Init sessionFactory here because the annotation of Spring 2.5 can not support override inject  
    6.      *    
    7.      * @param sessionFactory  
    8.      */  
    9.     @Autowired  
    10.     public void init(SessionFactory sessionFactory) {   
    11.         super.setSessionFactory(sessionFactory);   
    12.     }   
    13.   
    14.     public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {   
    15.         List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName);   
    16.         if(users.isEmpty()) {   
    17.             throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");   
    18.         }   
    19.         return users.get(0);   
    20.     }   
    21. }  


    這個(gè)實(shí)現(xiàn)非常簡單,由于我們的User對象已經(jīng)實(shí)現(xiàn)了UserDetails接口。所以我們只要使用Hibernate,根據(jù)userName取出相應(yīng)的User對象即可。注意在這里,由于我們對于User的關(guān)聯(lián)對象Roles都設(shè)置了lazy="false",所以我們無需擔(dān)心lazy loading的問題。

    4. 配置文件

    有了上面的代碼,一切都變得很簡單,重新定義authentication-provider節(jié)點(diǎn)即可。如果你使用Spring 2.5的Annotation配置功能,你甚至可以不需要在配置文件中定義securityManager的bean。

    Xml代碼 復(fù)制代碼
    1. <authentication-provider user-service-ref="securityManager">  
    2.     <password-encoder hash="md5"/>  
    3. </authentication-provider>  


    使用數(shù)據(jù)庫對資源進(jìn)行管理

    在完成了使用數(shù)據(jù)庫來進(jìn)行用戶和權(quán)限的管理之后,我們再來看看http配置的部分。在實(shí)際應(yīng)用中,我們不可能使用類似/**的方式來指定URL與權(quán)限ROLE的對應(yīng)關(guān)系,而是會(huì)針對某些URL,指定某些特定的ROLE。而URL與ROLE之間的映射關(guān)系最好可以進(jìn)行擴(kuò)展和配置。而URL屬于資源的一種,所以接下來,我們就來看看如何使用數(shù)據(jù)庫來對權(quán)限和資源的匹配關(guān)系進(jìn)行管理,并且將認(rèn)證匹配加入到Spring Security中去。

    權(quán)限和資源的設(shè)計(jì)

    上面我們講到,用戶(User)和權(quán)限(Role)之間是一個(gè)多對多的關(guān)系。那么權(quán)限(Role)和資源(Resource)之間呢?其實(shí)他們之間也是一個(gè)典型的多對多的關(guān)系,我們同樣用3張表來表示:

    Java代碼 復(fù)制代碼
    1. CREATE TABLE `role` (   
    2.   `id` int(11) NOT NULL auto_increment,   
    3.   `name` varchar(255default NULL,   
    4.   `description` varchar(255default NULL,   
    5.   PRIMARY KEY  (`id`)   
    6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;   
    7.   
    8. CREATE TABLE `resource` (   
    9.   `id` int(11) NOT NULL auto_increment,   
    10.   `type` varchar(255default NULL,   
    11.   `value` varchar(255default NULL,   
    12.   PRIMARY KEY  (`id`)   
    13. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;   
    14.   
    15. CREATE TABLE `role_resource` (   
    16.   `role_id` int(11) NOT NULL,   
    17.   `resource_id` int(11) NOT NULL,   
    18.   PRIMARY KEY  (`role_id`,`resource_id`),   
    19.   KEY `FKAEE599B751827FA1` (`role_id`),   
    20.   KEY `FKAEE599B7EFD18D21` (`resource_id`),   
    21.   CONSTRAINT `FKAEE599B751827FA1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`),   
    22.   CONSTRAINT `FKAEE599B7EFD18D21` FOREIGN KEY (`resource_id`) REFERENCES `resource` (`id`)   
    23. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  


    在這里Resource可能分成多種類型,比如MENU,URL,METHOD等等。

    針對資源的認(rèn)證

    針對資源的認(rèn)證,實(shí)際上應(yīng)該由Spring Security中的FilterSecurityInterceptor這個(gè)過濾器來完成。不過內(nèi)置的FilterSecurityInterceptor的實(shí)現(xiàn)往往無法滿足我們的要求,所以傳統(tǒng)的Acegi的方式,我們往往會(huì)替換FilterSecurityInterceptor的實(shí)現(xiàn),從而對URL等資源進(jìn)行認(rèn)證。

    不過在Spring Security中,由于默認(rèn)的攔截器鏈內(nèi)置了FilterSecurityInterceptor,而且上面我們也提到過,這個(gè)實(shí)現(xiàn)無法被替換。這就使我們犯了難。我們?nèi)绾螌Y源進(jìn)行認(rèn)證呢?

    實(shí)際上,我們雖然無法替換FilterSecurityInterceptor的默認(rèn)實(shí)現(xiàn),不過我們可以再實(shí)現(xiàn)一個(gè)類似的過濾器,并將我們自己的過濾器作為一個(gè)customer-filter,加到默認(rèn)的過濾器鏈的最后,從而完成整個(gè)過濾檢查。

    接下來我們就來看看一個(gè)完整的例子:

    1. 建立權(quán)限(Role)和資源(Resource)之間的關(guān)聯(lián)關(guān)系

    修改上面的權(quán)限(Role)的Entity定義:

    Java代碼 復(fù)制代碼
    1. @Entity  
    2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    3. public class Role {   
    4.        
    5.     @Id  
    6.     @GeneratedValue  
    7.     private Integer id;   
    8.        
    9.     private String name;   
    10.        
    11.     @ManyToMany(targetEntity = Resource.class, fetch = FetchType.EAGER)   
    12.     @JoinTable(name = "role_resource", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "resource_id"))   
    13.     @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    14.     private Set<Resource> resources;   
    15.   
    16.         // setters and getter   
    17. }  


    增加資源(Resource)的Entity定義:

    Java代碼 復(fù)制代碼
    1. @Entity  
    2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    3.   
    4. public class Resource {   
    5.   
    6.     @Id  
    7.     @GeneratedValue  
    8.     private Integer id;   
    9.        
    10.     private String type;   
    11.        
    12.     private String value;   
    13.        
    14.     @ManyToMany(mappedBy = "resources", targetEntity = Role.class, fetch = FetchType.EAGER)   
    15.     @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
    16.     private Set<Role> roles;   
    17.        
    18.     /**  
    19.      * The default constructor  
    20.      */  
    21.     public Resource() {   
    22.            
    23.     }   
    24. }  


    注意他們之間的多對多關(guān)系,以及他們之間關(guān)聯(lián)關(guān)系的緩存和lazy屬性設(shè)置。

    2. 在系統(tǒng)啟動(dòng)的時(shí)候,把所有的資源load到內(nèi)存作為緩存

    由于資源信息對于每個(gè)項(xiàng)目來說,相對固定,所以我們可以將他們在系統(tǒng)啟動(dòng)的時(shí)候就load到內(nèi)存作為緩存。這里做法很多,我給出的示例是將資源的存放在servletContext中。

    Java代碼 復(fù)制代碼
    1. public class ServletContextLoaderListener implements ServletContextListener {   
    2.   
    3.     /* (non-Javadoc)  
    4.      * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)  
    5.      */  
    6.     public void contextInitialized(ServletContextEvent servletContextEvent) {   
    7.         ServletContext servletContext = servletContextEvent.getServletContext();   
    8.         SecurityManager securityManager = this.getSecurityManager(servletContext);   
    9.            
    10.         Map<String, String> urlAuthorities = securityManager.loadUrlAuthorities();   
    11.         servletContext.setAttribute("urlAuthorities", urlAuthorities);   
    12.     }   
    13.   
    14.        
    15.     /* (non-Javadoc)  
    16.      * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)  
    17.      */  
    18.     public void contextDestroyed(ServletContextEvent servletContextEvent) {   
    19.         servletContextEvent.getServletContext().removeAttribute("urlAuthorities");   
    20.     }   
    21.   
    22.     /**  
    23.      * Get SecurityManager from ApplicationContext  
    24.      *   
    25.      * @param servletContext  
    26.      * @return  
    27.      */  
    28.     protected SecurityManager getSecurityManager(ServletContext servletContext) {   
    29.        return (SecurityManager) WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean("securityManager");    
    30.     }   
    31.   
    32. }  


    這里,我們看到了SecurityManager,這是一個(gè)接口,用于權(quán)限相關(guān)的邏輯處理。還記得之前我們使用數(shù)據(jù)庫管理User的時(shí)候所使用的一個(gè)實(shí)現(xiàn)類SecurityManagerSupport嘛?我們不妨依然借用這個(gè)類,讓它實(shí)現(xiàn)SecurityManager接口,來同時(shí)完成url的讀取工作。

    Java代碼 復(fù)制代碼
    1. @Service("securityManager")   
    2. public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService, SecurityManager {   
    3.        
    4.     /**  
    5.      * Init sessionFactory here because the annotation of Spring 2.5 can not support override inject  
    6.      *    
    7.      * @param sessionFactory  
    8.      */  
    9.     @Autowired  
    10.     public void init(SessionFactory sessionFactory) {   
    11.         super.setSessionFactory(sessionFactory);   
    12.     }   
    13.        
    14.     /* (non-Javadoc)  
    15.      * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)  
    16.      */  
    17.     public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {   
    18.         List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName);   
    19.         if(users.isEmpty()) {   
    20.             throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");   
    21.         }   
    22.         return users.get(0);   
    23.     }   
    24.        
    25.     /* (non-Javadoc)  
    26.      * @see com.javaeye.sample.security.SecurityManager#loadUrlAuthorities()  
    27.      */  
    28.     public Map<String, String> loadUrlAuthorities() {   
    29.         Map<String, String> urlAuthorities = new HashMap<String, String>();   
    30.         List<Resource> urlResources = getHibernateTemplate().find("FROM Resource resource WHERE resource.type = ?""URL");   
    31.         for(Resource resource : urlResources) {   
    32.             urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities());   
    33.         }   
    34.         return urlAuthorities;   
    35.     }      
    36. }  


    3. 編寫自己的FilterInvocationDefinitionSource實(shí)現(xiàn)類,對資源進(jìn)行認(rèn)證

    Java代碼 復(fù)制代碼
    1. public class SecureResourceFilterInvocationDefinitionSource implements FilterInvocationDefinitionSource, InitializingBean {   
    2.        
    3.     private UrlMatcher urlMatcher;   
    4.   
    5.     private boolean useAntPath = true;   
    6.        
    7.     private boolean lowercaseComparisons = true;   
    8.        
    9.     /**  
    10.      * @param useAntPath the useAntPath to set  
    11.      */  
    12.     public void setUseAntPath(boolean useAntPath) {   
    13.         this.useAntPath = useAntPath;   
    14.     }   
    15.        
    16.     /**  
    17.      * @param lowercaseComparisons  
    18.      */  
    19.     public void setLowercaseComparisons(boolean lowercaseComparisons) {   
    20.         this.lowercaseComparisons = lowercaseComparisons;   
    21.     }   
    22.        
    23.     /* (non-Javadoc)  
    24.      * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()  
    25.      */  
    26.     public void afterPropertiesSet() throws Exception {   
    27.            
    28.         // default url matcher will be RegexUrlPathMatcher   
    29.         this.urlMatcher = new RegexUrlPathMatcher();   
    30.            
    31.         if (useAntPath) {  // change the implementation if required   
    32.             this.urlMatcher = new AntUrlPathMatcher();   
    33.         }   
    34.            
    35.         // Only change from the defaults if the attribute has been set   
    36.         if ("true".equals(lowercaseComparisons)) {   
    37.             if (!this.useAntPath) {   
    38.                 ((RegexUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(true);   
    39.             }   
    40.         } else if ("false".equals(lowercaseComparisons)) {   
    41.             if (this.useAntPath) {   
    42.                 ((AntUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(false);   
    43.             }   
    44.         }   
    45.            
    46.     }   
    47.        
    48.     /* (non-Javadoc)  
    49.      * @see org.springframework.security.intercept.ObjectDefinitionSource#getAttributes(java.lang.Object)  
    50.      */  
    51.     public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException {   
    52.            
    53.         FilterInvocation filterInvocation = (FilterInvocation) filter;   
    54.         String requestURI = filterInvocation.getRequestUrl();   
    55.         Map<String, String> urlAuthorities = this.getUrlAuthorities(filterInvocation);   
    56.            
    57.         String grantedAuthorities = null;   
    58.         for(Iterator<Map.Entry<String, String>> iter = urlAuthorities.entrySet().iterator(); iter.hasNext();) {   
    59.             Map.Entry<String, String> entry = iter.next();   
    60.             String url = entry.getKey();   
    61.                
    62.             if(urlMatcher.pathMatchesUrl(url, requestURI)) {   
    63.                 grantedAuthorities = entry.getValue();   
    64.                 break;   
    65.             }   
    66.                
    67.         }   
    68.            
    69.         if(grantedAuthorities != null) {   
    70.             ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor();   
    71.             configAttrEditor.setAsText(grantedAuthorities);   
    72.             return (ConfigAttributeDefinition) configAttrEditor.getValue();   
    73.         }   
    74.            
    75.         return null;   
    76.     }   
    77.   
    78.     /* (non-Javadoc)  
    79.      * @see org.springframework.security.intercept.ObjectDefinitionSource#getConfigAttributeDefinitions()  
    80.      */  
    81.     @SuppressWarnings("unchecked")   
    82.     public Collection getConfigAttributeDefinitions() {   
    83.         return null;   
    84.     }   
    85.   
    86.     /* (non-Javadoc)  
    87.      * @see org.springframework.security.intercept.ObjectDefinitionSource#supports(java.lang.Class)  
    88.      */  
    89.     @SuppressWarnings("unchecked")   
    90.     public boolean supports(Class clazz) {   
    91.         return true;   
    92.     }   
    93.        
    94.     /**  
    95.      *   
    96.      * @param filterInvocation  
    97.      * @return  
    98.      */  
    99.     @SuppressWarnings("unchecked")   
    100.     private Map<String, String> getUrlAuthorities(FilterInvocation filterInvocation) {   
    101.         ServletContext servletContext = filterInvocation.getHttpRequest().getSession().getServletContext();   
    102.         return (Map<String, String>)servletContext.getAttribute("urlAuthorities");   
    103.     }   
    104.   
    105. }  


    4. 配置文件修改

    接下來,我們來修改一下Spring Security的配置文件,把我們自定義的這個(gè)過濾器插入到過濾器鏈中去。

    Xml代碼 復(fù)制代碼
    1. <beans:beans xmlns="http://www.springframework.org/schema/security"  
    2.     xmlns:beans="http://www.springframework.org/schema/beans"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    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.        
    7.     <beans:bean id="loggerListener" class="org.springframework.security.event.authentication.LoggerListener" />  
    8.        
    9.     <http access-denied-page="/403.jsp" >  
    10.         <intercept-url pattern="/static/**" filters="none" />  
    11.         <intercept-url pattern="/template/**" filters="none" />  
    12.         <intercept-url pattern="/" filters="none" />  
    13.         <intercept-url pattern="/login.jsp" filters="none" />  
    14.         <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/index" />  
    15.         <logout logout-success-url="/login.jsp"/>  
    16.         <http-basic />  
    17.     </http>  
    18.   
    19.     <authentication-manager alias="authenticationManager"/>  
    20.        
    21.     <authentication-provider user-service-ref="securityManager">  
    22.         <password-encoder hash="md5"/>  
    23.     </authentication-provider>  
    24.        
    25.     <beans:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">  
    26.         <beans:property name="allowIfAllAbstainDecisions" value="false"/>  
    27.         <beans:property name="decisionVoters">  
    28.             <beans:list>  
    29.                 <beans:bean class="org.springframework.security.vote.RoleVoter"/>  
    30.                 <beans:bean class="org.springframework.security.vote.AuthenticatedVoter"/>  
    31.             </beans:list>  
    32.         </beans:property>  
    33.     </beans:bean>  
    34.        
    35.     <beans:bean id="resourceSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor">  
    36.         <beans:property name="authenticationManager" ref="authenticationManager"/>  
    37.         <beans:property name="accessDecisionManager" ref="accessDecisionManager"/>  
    38.         <beans:property name="objectDefinitionSource" ref="secureResourceFilterInvocationDefinitionSource" />  
    39.         <beans:property name="observeOncePerRequest" value="false" />  
    40.         <custom-filter after="LAST" />  
    41.     </beans:bean>  
    42.        
    43.     <beans:bean id="secureResourceFilterInvocationDefinitionSource" class="com.javaeye.sample.security.interceptor.SecureResourceFilterInvocationDefinitionSource" />  
    44.        
    45. </beans:beans>  


    請注意,由于我們所實(shí)現(xiàn)的,是FilterSecurityInterceptor中的一個(gè)開放接口,所以我們實(shí)際上定義了一個(gè)新的bean,并通過<custom-filter after="LAST" />插入到過濾器鏈中去。

    Spring Security對象的訪問

    1. 訪問當(dāng)前登錄用戶

    Spring Security提供了一個(gè)線程安全的對象:SecurityContextHolder,通過這個(gè)對象,我們可以訪問當(dāng)前的登錄用戶。我寫了一個(gè)類,可以通過靜態(tài)方法去讀取:

    Java代碼 復(fù)制代碼
    1. public class SecurityUserHolder {   
    2.   
    3.     /**  
    4.      * Returns the current user  
    5.      *   
    6.      * @return  
    7.      */  
    8.     public static User getCurrentUser() {   
    9.         return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();   
    10.     }   
    11.   
    12. }  


    2. 訪問當(dāng)前登錄用戶所擁有的權(quán)限

    通過上面的分析,我們知道,用戶所擁有的所有權(quán)限,其實(shí)是通過UserDetails接口中的getAuthorities()方法獲得的。只要實(shí)現(xiàn)這個(gè)接口,就能實(shí)現(xiàn)需求。在我的代碼中,不僅實(shí)現(xiàn)了這個(gè)接口,還在上面做了點(diǎn)小文章,這樣我們可以獲得一個(gè)用戶所擁有權(quán)限的字符串表示:

    Java代碼 復(fù)制代碼
    1. /* (non-Javadoc)  
    2.  * @see org.springframework.security.userdetails.UserDetails#getAuthorities()  
    3.  */  
    4. public GrantedAuthority[] getAuthorities() {   
    5.     List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());   
    6.     for(Role role : roles) {   
    7.         grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));   
    8.     }   
    9.        return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);   
    10. }   
    11.   
    12. /**  
    13.  * Returns the authorites string  
    14.  *   
    15.  * eg.   
    16.  *    downpour --- ROLE_ADMIN,ROLE_USER  
    17.  *    robbin --- ROLE_ADMIN  
    18.  *   
    19.  * @return  
    20.  */  
    21. public String getAuthoritiesString() {   
    22.     List<String> authorities = new ArrayList<String>();   
    23.     for(GrantedAuthority authority : this.getAuthorities()) {   
    24.         authorities.add(authority.getAuthority());   
    25.     }   
    26.     return StringUtils.join(authorities, ",");   
    27. }  


    3. 訪問當(dāng)前登錄用戶能夠訪問的資源

    這就涉及到用戶(User),權(quán)限(Role)和資源(Resource)三者之間的對應(yīng)關(guān)系。我同樣在User對象中實(shí)現(xiàn)了一個(gè)方法:

    Java代碼 復(fù)制代碼
    1. /**  
    2.  * @return the roleResources  
    3.  */  
    4. public Map<String, List<Resource>> getRoleResources() {   
    5.     // init roleResources for the first time   
    6.     if(this.roleResources == null) {               
    7.         this.roleResources = new HashMap<String, List<Resource>>();   
    8.                
    9.         for(Role role : this.roles) {   
    10.             String roleName = role.getName();   
    11.             Set<Resource> resources = role.getResources();   
    12.             for(Resource resource : resources) {   
    13.                 String key = roleName + "_" + resource.getType();   
    14.                     if(!this.roleResources.containsKey(key)) {   
    15.                         this.roleResources.put(key, new ArrayList<Resource>());   
    16.                 }   
    17.                     this.roleResources.get(key).add(resource);                     
    18.             }   
    19.         }   
    20.                
    21.     }   
    22.     return this.roleResources;   
    23. }  


    這里,會(huì)在User對象中設(shè)置一個(gè)緩存機(jī)制,在第一次取的時(shí)候,通過遍歷User所有的Role,獲取相應(yīng)的Resource信息。

    轉(zhuǎn)自:http://www.javaeye.com/topic/319965
    posted on 2009-02-05 22:01 CONAN 閱讀(496) 評(píng)論(0)  編輯  收藏 所屬分類: Spring
    主站蜘蛛池模板: 免费看的成人yellow视频| 亚洲最大黄色网站| 无码 免费 国产在线观看91| 精品国产免费一区二区| 亚洲一区中文字幕在线电影网| 无码人妻一区二区三区免费看| 中文字幕久久亚洲一区| 免费视频成人国产精品网站| 成人免费视频国产| 亚洲色欲色欱wwW在线| 曰批全过程免费视频在线观看| 亚洲国产成人久久99精品| 2021在线永久免费视频| 亚洲人成在线播放网站岛国| 国产午夜免费高清久久影院| 国产自偷亚洲精品页65页| www成人免费视频| 亚洲片一区二区三区| 四虎精品成人免费视频| 亚洲国产成人a精品不卡在线| 亚洲国产一区二区三区在线观看 | 国产精品99爱免费视频| 亚洲国产精品人人做人人爽| 黄色一级毛片免费| 亚洲精品国产精品乱码不卞 | 日韩精品无码人妻免费视频| 亚洲欧美成人综合久久久| 成人一a毛片免费视频| 亚洲日韩中文字幕一区| 女人18毛片免费观看| 亚洲人片在线观看天堂无码| 在线观看免费大黄网站| 亚洲成av人片在线天堂无| 日本视频免费在线| 特级一级毛片免费看| 亚洲欧洲一区二区三区| a级毛片视频免费观看| 亚洲AV第一页国产精品| 84pao强力永久免费高清| 亚洲小视频在线播放| 最近的免费中文字幕视频|