Spring Security配置

論壇上看了不少Spring Security的相關文章。這些文章基本上都還是基於Acegi-1.X的配置方式,而主要的配置示例也來自於SpringSide的貢獻。

衆所周知,Spring Security針對Acegi的一個重大的改進就在於其配置方式大大簡化了。所以如果配置還是基於Acegi-1.X這樣比較繁瑣的配置方式的話,那麼我們還不如直接使用Acegi而不要去升級了。所以在這裏,我將結合一個示例,重點討論一下Spring Security 2是如何進行配置簡化的。

搭建基礎環境

首先我們爲示例搭建基本的開發環境,環境的搭建方式,可以參考我的另外一篇文章:http://www.iteye.com/wiki/struts2/1321-struts2-development-environment-to-build

整個環境的搭建包括:創建合適的目錄結構、加入了合適的Library,加入了基本的Jetty啓動類、加入基本的配置文件等。最終的項目結構,可以參考我的附件。

參考文檔

這裏主要的參考文檔是Spring Security的自帶的Reference。網絡上有一個它的中文翻譯,地址如下:http://www.family168.com/tutorial/springsecurity/html/springsecurity.html

除此之外,springside有一個比較完整的例子,不過是基於Acegi的,我也參閱了其中的一些實現。

Spring Security基本配置

Spring Security是基於Spring的的權限認證框架,對於Spring和Acegi已經比較熟悉的同學對於之前的配置方式應該已經非常瞭解。接下來的例子,將向大家展示Spring Security基於schema的配置方式。

最小化配置

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

Xml代碼 複製代碼 收藏代碼
  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>  



這個Filter會攔截所有的URL請求,並且對這些URL請求進行Spring Security的驗證。

注意,springSecurityFilterChain這個名稱是由命名空間默認創建的用於處理web安全的一個內部的bean的id。所以你在你的Spring配置文件中,不應該再使用這個id作爲你的bean。

與Acegi的配置不同,Acegi需要自行聲明一個Spring的bean來作爲Filter的實現,而使用Spring Security後,無需再額外定義bean,而是使用<http>元素進行配置。

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

Xml代碼 複製代碼 收藏代碼
  1. <http auto-config='true'>  
  2.     <intercept-url pattern="/**" access="ROLE_USER" />  
  3. </http>  



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

3. 配置UserDetailsService來指定用戶和權限

接下來,我們來配置一個UserDetailsService來指定用戶和權限:

Xml代碼 複製代碼 收藏代碼
  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的權限,robbin擁有ROLE_USER權限,QuakeWang擁有ROLE_ADMIN的權限

4. 小結

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

如果你具備Acegi的知識,你會發現,有很多Acegi中的元素,在Spring Security中都沒有了,這些元素包括:表單和基本登錄選項、密碼編碼器、Remember-Me認證等等。

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

剖析基本配置元素

1. 有關auto-config屬性

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

Xml代碼 複製代碼 收藏代碼
  1. <http>  
  2.     <intercept-url pattern="/**" access="ROLE_USER" />  
  3.     <form-login />  
  4.     <anonymous />  
  5.     <http-basic />  
  6.     <logout />  
  7.     <remember-me />  
  8. </http>  



這些元素分別與登錄認證,匿名認證,基本認證,註銷處理和remember-me對應。 他們擁有各自的屬性,可以改變他們的具體行爲。

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

2. 與Acegi的比較

我們仔細觀察一下沒有auto-config的那段XML配置,是不是熟悉多了?讓我們來將基於命名空間的配置與傳統的Acegi的bean的配置做一個比較,我們會發現以下的區別:

1) 基於命名空間的配置更加簡潔,可維護性更強

例如,基於命名空間進行登錄認證的配置代碼,可能像這樣:

Xml代碼 複製代碼 收藏代碼
  1. <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/work" />  



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

Xml代碼 複製代碼 收藏代碼
  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>  



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

2) 基於命名空間的配置,我們無需再擔心由於過濾器鏈的順序而導致的錯誤

以前,Acegi在缺乏默認內置配置的情況下,你需要自己來定義所有的bean,並指定這些bean在過濾器鏈中的順序。一旦順序錯了,很容易發生錯誤。而現在,過濾器鏈的順序被默認指定,你不需要在擔心由於順序的錯誤而導致的錯誤。

3. 過濾器鏈在哪裏

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

Xml代碼 複製代碼 收藏代碼
  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>  



其中,每個過濾器鏈都將對應於Spring配置文件中的bean的id。

現在,在Spring Security中,我們將看不到這些配置,這些配置都被內置在<http>節點中。讓我們來看看這些默認的,已經被內置的過濾器:


這些過濾器已經被Spring容器默認內置註冊,這也就是我們不再需要在配置文件中定義那麼多bean的原因。

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

當然,這樣的規定是否合理,有待進一步討論。因爲實際上在很多時候,我們希望覆蓋過濾器鏈中的某個過濾器的默認行爲。而Spring Security的這種規定在一定程度上限制了我們的行爲。

不過Spring Security允許你把你自己的過濾器添加到隊列中,使用custom-filter元素,並且指定你的過濾器應該出現的位置:

Xml代碼 複製代碼 收藏代碼
  1. <beans:bean id="myFilter" class="com.mycompany.MySpecialAuthenticationFilter">  
  2.     <custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/>  
  3. </beans:bean>  



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

這個特性或許能夠在一定程度上彌補Spring Security的死板規定,而在之後的應用中,我也會把它作爲切入點,對資源進行管理。

另外,我需要補充一點的是,對於在http/intercept-url中沒有進行定義的URL,將會默認使用系統內置的過濾器鏈進行權限認證。所以,你並不需要在http/intercept-url中額外定義一個類似/**的匹配規則。

使用數據庫對用戶和權限進行管理

一般來說,我們都有使用數據庫對用戶和權限進行管理的需求,而不會把用戶寫死在配置文件裏。所以,我們接下來就重點討論使用數據庫對用戶和權限進行管理的方法。

用戶和權限的關係設計

在此之前,我們首先需要討論一下用戶(User)和權限(Role)之間的關係。Spring Security在默認情況下,把這兩者當作一對多的關係進行處理。所以,在Spring Security中對這兩個對象所採用的表結構關係大概像這樣:

Java代碼 複製代碼 收藏代碼
  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. );  
CREATE TABLE users (
  username VARCHAR(50) NOT NULL PRIMARY KEY,
  password VARCHAR(50) NOT NULL,
  enabled BIT NOT NULL
);

CREATE TABLE authorities (
  username VARCHAR(50) NOT NULL,
  authority VARCHAR(50) NOT NULL
);



不過這種設計方式在實際生產環境中基本上不會採用。一般來說,我們會使用邏輯主鍵ID來標示每個User和每個Authorities(Role)。而且從典型意義上講,他們之間是一個多對多的關係,我們會採用3張表來表示,下面是我在MySQL中建立的3張表的schema示例:

Java代碼 複製代碼 收藏代碼
  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;  
CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `password` varchar(255) default NULL,
  `disabled` int(1) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `role` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `user_role` (
  `user_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  PRIMARY KEY  (`user_id`,`role_id`),
  UNIQUE KEY `role_id` (`role_id`),
  KEY `FK143BF46AF6AD4381` (`user_id`),
  KEY `FK143BF46A51827FA1` (`role_id`),
  CONSTRAINT `FK143BF46A51827FA1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`),
  CONSTRAINT `FK143BF46AF6AD4381` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



通過配置SQL來模擬用戶和權限

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

Xml代碼 複製代碼 收藏代碼
  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>  



這裏給出的是一個使用SQL進行模擬用戶和權限的示例。其中你需要爲運行SQL準備相應的dataSource。這個dataSource應該對應於Spring中的某個bean的定義。

從這段配置模擬用戶和權限的情況來看,實際上Spring Security對於用戶,需要username,password,accountEnabled三個字段。對於權限,它需要的是username和authority2個字段。

也就是說,如果我們能夠通過其他的方式,模擬上面的這些對象,並插入到Spring Security中去,我們同樣能夠實現用戶和權限的認證。接下來,我們就來看看我們如何通過自己的實現,來完成這件事情。

通過擴展Spring Security的默認實現來進行用戶和權限的管理

事實上,Spring Security提供了2個認證的接口,分別用於模擬用戶和權限,以及讀取用戶和權限的操作方法。這兩個接口分別是:UserDetails和UserDetailsService。

Java代碼 複製代碼 收藏代碼
  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. }  
public interface UserDetails extends Serializable {
    
    GrantedAuthority[] getAuthorities();

    String getPassword();

    String getUsername();

    boolean isAccountNonExpired();

    boolean isAccountNonLocked();

    boolean isCredentialsNonExpired();

    boolean isEnabled();
}


Java代碼 複製代碼 收藏代碼
  1. public interface UserDetailsService {   
  2.     UserDetails loadUserByUsername(String username)   
  3.         throws UsernameNotFoundException, DataAccessException;   
  4. }  
public interface UserDetailsService {
    UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException;
}



非常清楚,一個接口用於模擬用戶,另外一個用於模擬讀取用戶的過程。所以我們可以通過實現這兩個接口,來完成使用數據庫對用戶和權限進行管理的需求。在這裏,我將給出一個使用Hibernate來定義用戶和權限之間關係的示例。

1. 定義User類和Role類,使他們之間形成多對多的關係

Java代碼 複製代碼 收藏代碼
  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. }  
@Entity
@Proxy(lazy = false)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {
	
	private static final long serialVersionUID = 8026813053768023527L;

    @Id
	@GeneratedValue
	private Integer id;
	
	private String name;
	
	private String password;
	
	private boolean disabled;
	
	@ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	private Set<Role> roles;

        // setters and getters
}


Java代碼 複製代碼 收藏代碼
  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. }  
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role {
	
	@Id
	@GeneratedValue
	private Integer id;
	
	private String name;
        
        // setters and getters
}



請注意這裏的Annotation的寫法。同時,我爲User和Role之間配置了緩存。並且將他們之間的關聯關係設置的lazy屬性設置成false,從而保證在User對象取出之後的使用不會因爲脫離session的生命週期而產生lazy loading問題。

2. 使User類實現UserDetails接口

接下來,我們讓User類去實現UserDetails接口:

Java代碼 複製代碼 收藏代碼
  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. }  
@Entity
@Proxy(lazy = false)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User implements UserDetails {
	
	private static final long serialVersionUID = 8026813053768023527L;

    @Id
	@GeneratedValue
	private Integer id;
	
	private String name;
	
	private String password;
	
	private boolean disabled;
	
	@ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	private Set<Role> roles;
	
	/**
	 * The default constructor
	 */
	public User() {
		
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#getAuthorities()
	 */
	public GrantedAuthority[] getAuthorities() {
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
    	for(Role role : roles) {
    		grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));
    	}
        return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#getPassword()
	 */
	public String getPassword() {
		return password;
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#getUsername()
	 */
	public String getUsername() {
		return name;
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#isAccountNonExpired()
	 */
	public boolean isAccountNonExpired() {
		return true;
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#isAccountNonLocked()
	 */
	public boolean isAccountNonLocked() {
		return true;
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#isCredentialsNonExpired()
	 */
	public boolean isCredentialsNonExpired() {
		return true;
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#isEnabled()
	 */
	public boolean isEnabled() {
		return !this.disabled;
	}
      
      // setters and getters
}



實現UserDetails接口中的每個函數,其實沒什麼很大的難度,除了其中的一個函數我需要額外強調一下:

Java代碼 複製代碼 收藏代碼
  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. }  
/* (non-Javadoc)
 * @see org.springframework.security.userdetails.UserDetails#getAuthorities()
 */
public GrantedAuthority[] getAuthorities() {
	List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
   	for(Role role : roles) {
	    grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));
    	}
        return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);
}



這個函數的實際作用是根據User返回這個User所擁有的權限列表。如果以上面曾經用過的例子來說,如果當前User是downpour,我需要得到ROLE_USER和ROLE_ADMIN;如果當前User是robbin,我需要得到ROLE_USER。

瞭解了含義,實現就變得簡單了,由於User與Role是多對多的關係,我們可以通過User得到所有這個User所對應的Role,並把這些Role的name拼裝起來返回。

由此可見,實現UserDetails接口,並沒有什麼神祕的地方,它只是實際上在一定程度上只是代替了使用配置文件的硬編碼:

Xml代碼 複製代碼 收藏代碼
  1. <user name="downpour" password="downpour" authorities="ROLE_USER, ROLE_ADMIN" />  



3. 實現UserDetailsService接口

Java代碼 複製代碼 收藏代碼
  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. }  
@Repository("securityManager")
public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService {

    /**
     * Init sessionFactory here because the annotation of Spring 2.5 can not support override inject
     *  
     * @param sessionFactory
     */
    @Autowired
    public void init(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
        List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName);
        if(users.isEmpty()) {
            throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");
        }
        return users.get(0);
    }
}



這個實現非常簡單,由於我們的User對象已經實現了UserDetails接口。所以我們只要使用Hibernate,根據userName取出相應的User對象即可。注意在這裏,由於我們對於User的關聯對象Roles都設置了lazy="false",所以我們無需擔心lazy loading的問題。

4. 配置文件

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

Xml代碼 複製代碼 收藏代碼
  1. <authentication-provider user-service-ref="securityManager">  
  2.     <password-encoder hash="md5"/>  
  3. </authentication-provider>  



使用數據庫對資源進行管理

在完成了使用數據庫來進行用戶和權限的管理之後,我們再來看看http配置的部分。在實際應用中,我們不可能使用類似/**的方式來指定URL與權限ROLE的對應關係,而是會針對某些URL,指定某些特定的ROLE。而URL與ROLE之間的映射關係最好可以進行擴展和配置。而URL屬於資源的一種,所以接下來,我們就來看看如何使用數據庫來對權限和資源的匹配關係進行管理,並且將認證匹配加入到Spring Security中去。

權限和資源的設計

上面我們講到,用戶(User)和權限(Role)之間是一個多對多的關係。那麼權限(Role)和資源(Resource)之間呢?其實他們之間也是一個典型的多對多的關係,我們同樣用3張表來表示:

Java代碼 複製代碼 收藏代碼
  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;  
CREATE TABLE `role` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `description` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `resource` (
  `id` int(11) NOT NULL auto_increment,
  `type` varchar(255) default NULL,
  `value` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `role_resource` (
  `role_id` int(11) NOT NULL,
  `resource_id` int(11) NOT NULL,
  PRIMARY KEY  (`role_id`,`resource_id`),
  KEY `FKAEE599B751827FA1` (`role_id`),
  KEY `FKAEE599B7EFD18D21` (`resource_id`),
  CONSTRAINT `FKAEE599B751827FA1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`),
  CONSTRAINT `FKAEE599B7EFD18D21` FOREIGN KEY (`resource_id`) REFERENCES `resource` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



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

針對資源的認證

針對資源的認證,實際上應該由Spring Security中的FilterSecurityInterceptor這個過濾器來完成。不過內置的FilterSecurityInterceptor的實現往往無法滿足我們的要求,所以傳統的Acegi的方式,我們往往會替換FilterSecurityInterceptor的實現,從而對URL等資源進行認證。

不過在Spring Security中,由於默認的攔截器鏈內置了FilterSecurityInterceptor,而且上面我們也提到過,這個實現無法被替換。這就使我們犯了難。我們如何對資源進行認證呢?

實際上,我們雖然無法替換FilterSecurityInterceptor的默認實現,不過我們可以再實現一個類似的過濾器,並將我們自己的過濾器作爲一個customer-filter,加到默認的過濾器鏈的最後,從而完成整個過濾檢查。

接下來我們就來看看一個完整的例子:

1. 建立權限(Role)和資源(Resource)之間的關聯關係

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

Java代碼 複製代碼 收藏代碼
  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. }  
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role {
	
	@Id
	@GeneratedValue
	private Integer id;
	
	private String name;
	
	@ManyToMany(targetEntity = Resource.class, fetch = FetchType.EAGER)
    @JoinTable(name = "role_resource", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "resource_id"))
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	private Set<Resource> resources;

        // setters and getter
}



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

Java代碼 複製代碼 收藏代碼
  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. }  
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

public class Resource {

	@Id
    @GeneratedValue
	private Integer id;
	
	private String type;
	
	private String value;
	
	@ManyToMany(mappedBy = "resources", targetEntity = Role.class, fetch = FetchType.EAGER)
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	private Set<Role> roles;
	
	/**
	 * The default constructor
	 */
	public Resource() {
		
	}
}



注意他們之間的多對多關係,以及他們之間關聯關係的緩存和lazy屬性設置。

2. 在系統啓動的時候,把所有的資源load到內存作爲緩存

由於資源信息對於每個項目來說,相對固定,所以我們可以將他們在系統啓動的時候就load到內存作爲緩存。這裏做法很多,我給出的示例是將資源的存放在servletContext中。

Java代碼 複製代碼 收藏代碼
  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. }  
public class ServletContextLoaderListener implements ServletContextListener {

    /* (non-Javadoc)
     * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        SecurityManager securityManager = this.getSecurityManager(servletContext);
        
        Map<String, String> urlAuthorities = securityManager.loadUrlAuthorities();
        servletContext.setAttribute("urlAuthorities", urlAuthorities);
    }

    
    /* (non-Javadoc)
     * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        servletContextEvent.getServletContext().removeAttribute("urlAuthorities");
    }

    /**
     * Get SecurityManager from ApplicationContext
     * 
     * @param servletContext
     * @return
     */
    protected SecurityManager getSecurityManager(ServletContext servletContext) {
       return (SecurityManager) WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean("securityManager"); 
    }

}



這裏,我們看到了SecurityManager,這是一個接口,用於權限相關的邏輯處理。還記得之前我們使用數據庫管理User的時候所使用的一個實現類SecurityManagerSupport嘛?我們不妨依然借用這個類,讓它實現SecurityManager接口,來同時完成url的讀取工作。

Java代碼 複製代碼 收藏代碼
  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. }  
@Service("securityManager")
public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService, SecurityManager {
    
    /**
     * Init sessionFactory here because the annotation of Spring 2.5 can not support override inject
     *  
     * @param sessionFactory
     */
    @Autowired
    public void init(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }
    
    /* (non-Javadoc)
     * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
        List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName);
        if(users.isEmpty()) {
            throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");
        }
        return users.get(0);
    }
    
    /* (non-Javadoc)
     * @see com.javaeye.sample.security.SecurityManager#loadUrlAuthorities()
     */
    public Map<String, String> loadUrlAuthorities() {
        Map<String, String> urlAuthorities = new HashMap<String, String>();
        List<Resource> urlResources = getHibernateTemplate().find("FROM Resource resource WHERE resource.type = ?", "URL");
        for(Resource resource : urlResources) {
            urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities());
        }
        return urlAuthorities;
    }   
}



3. 編寫自己的FilterInvocationDefinitionSource實現類,對資源進行認證

Java代碼 複製代碼 收藏代碼
  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. }  
public class SecureResourceFilterInvocationDefinitionSource implements FilterInvocationDefinitionSource, InitializingBean {
    
    private UrlMatcher urlMatcher;

    private boolean useAntPath = true;
    
    private boolean lowercaseComparisons = true;
    
    /**
     * @param useAntPath the useAntPath to set
     */
    public void setUseAntPath(boolean useAntPath) {
        this.useAntPath = useAntPath;
    }
    
    /**
     * @param lowercaseComparisons
     */
    public void setLowercaseComparisons(boolean lowercaseComparisons) {
        this.lowercaseComparisons = lowercaseComparisons;
    }
    
    /* (non-Javadoc)
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        
        // default url matcher will be RegexUrlPathMatcher
        this.urlMatcher = new RegexUrlPathMatcher();
        
        if (useAntPath) {  // change the implementation if required
            this.urlMatcher = new AntUrlPathMatcher();
        }
        
        // Only change from the defaults if the attribute has been set
        if ("true".equals(lowercaseComparisons)) {
            if (!this.useAntPath) {
                ((RegexUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(true);
            }
        } else if ("false".equals(lowercaseComparisons)) {
            if (this.useAntPath) {
                ((AntUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(false);
            }
        }
        
    }
    
    /* (non-Javadoc)
     * @see org.springframework.security.intercept.ObjectDefinitionSource#getAttributes(java.lang.Object)
     */
    public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException {
        
        FilterInvocation filterInvocation = (FilterInvocation) filter;
        String requestURI = filterInvocation.getRequestUrl();
        Map<String, String> urlAuthorities = this.getUrlAuthorities(filterInvocation);
        
        String grantedAuthorities = null;
        for(Iterator<Map.Entry<String, String>> iter = urlAuthorities.entrySet().iterator(); iter.hasNext();) {
            Map.Entry<String, String> entry = iter.next();
            String url = entry.getKey();
            
            if(urlMatcher.pathMatchesUrl(url, requestURI)) {
                grantedAuthorities = entry.getValue();
                break;
            }
            
        }
        
        if(grantedAuthorities != null) {
            ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor();
            configAttrEditor.setAsText(grantedAuthorities);
            return (ConfigAttributeDefinition) configAttrEditor.getValue();
        }
        
        return null;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.intercept.ObjectDefinitionSource#getConfigAttributeDefinitions()
     */
    @SuppressWarnings("unchecked")
	public Collection getConfigAttributeDefinitions() {
        return null;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.intercept.ObjectDefinitionSource#supports(java.lang.Class)
     */
    @SuppressWarnings("unchecked")
	public boolean supports(Class clazz) {
        return true;
    }
    
    /**
     * 
     * @param filterInvocation
     * @return
     */
    @SuppressWarnings("unchecked")
	private Map<String, String> getUrlAuthorities(FilterInvocation filterInvocation) {
        ServletContext servletContext = filterInvocation.getHttpRequest().getSession().getServletContext();
        return (Map<String, String>)servletContext.getAttribute("urlAuthorities");
    }

}



4. 配置文件修改

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

Xml代碼 複製代碼 收藏代碼
  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>  



請注意,由於我們所實現的,是FilterSecurityInterceptor中的一個開放接口,所以我們實際上定義了一個新的bean,並通過<custom-filter after="LAST" />插入到過濾器鏈中去。

Spring Security對象的訪問

1. 訪問當前登錄用戶

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

Java代碼 複製代碼 收藏代碼
  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. }  
public class SecurityUserHolder {

	/**
	 * Returns the current user
	 * 
	 * @return
	 */
	public static User getCurrentUser() {
		return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}

}



2. 訪問當前登錄用戶所擁有的權限

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

Java代碼 複製代碼 收藏代碼
  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. }  
	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#getAuthorities()
	 */
	public GrantedAuthority[] getAuthorities() {
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
    	for(Role role : roles) {
    		grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));
    	}
        return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);
	}
	
	/**
	 * Returns the authorites string
	 * 
	 * eg. 
	 *    downpour --- ROLE_ADMIN,ROLE_USER
	 *    robbin --- ROLE_ADMIN
	 * 
	 * @return
	 */
	public String getAuthoritiesString() {
	    List<String> authorities = new ArrayList<String>();
	    for(GrantedAuthority authority : this.getAuthorities()) {
	        authorities.add(authority.getAuthority());
	    }
	    return StringUtils.join(authorities, ",");
	}



3. 訪問當前登錄用戶能夠訪問的資源

這就涉及到用戶(User),權限(Role)和資源(Resource)三者之間的對應關係。我同樣在User對象中實現了一個方法:

Java代碼 複製代碼 收藏代碼
  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. }  
/**
 * @return the roleResources
 */
public Map<String, List<Resource>> getRoleResources() {
	// init roleResources for the first time
	if(this.roleResources == null) {			
		this.roleResources = new HashMap<String, List<Resource>>();
			
		for(Role role : this.roles) {
			String roleName = role.getName();
			Set<Resource> resources = role.getResources();
			for(Resource resource : resources) {
				String key = roleName + "_" + resource.getType();
					if(!this.roleResources.containsKey(key)) {
						this.roleResources.put(key, new ArrayList<Resource>());
				}
					this.roleResources.get(key).add(resource);					
			}
		}
			
	}
	return this.roleResources;
}



這裏,會在User對象中設置一個緩存機制,在第一次取的時候,通過遍歷User所有的Role,獲取相應的Resource信息。

代碼示例

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