?論壇上看了不少Spring Security的相關文章。這些文章基本上都還是基于Acegi-1.X的配置方式,而主要的配置示例也來自于SpringSide的貢獻。 眾所周知,Spring Security針對Acegi的一個重大的改進就在于其配置方式大大簡化了。所以如果配置還是基于Acegi-1.X這樣比較繁瑣的配置方式的話,那么我們還不如直接使用Acegi而不要去升級了。所以在這里,我將結合一個示例,重點討論一下Spring Security 2是如何進行配置簡化的。 搭建基礎環境 首先我們為示例搭建基本的開發環境,環境的搭建方式,可以參考我的另外一篇文章:http://www.javaeye.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代碼
?? < filter > ??????< filter-name > springSecurityFilterChain</ filter-name > ?? ????< filter-class > org.springframework.web.filter.DelegatingFilterProxy</ filter-class > ?? </ filter > ??< filter-mapping > ??????< filter-name > springSecurityFilterChain</ filter-name > ?? ????< url-pattern > /*</ url-pattern > ?? </ filter-mapping > ??
<!-- Spring security Filter -->
<filter><filter-name>springSecurityFilterChain</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping><filter-name>springSecurityFilterChain</filter-name><url-pattern>/*</url-pattern>
</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代碼
< http ?auto-config ='true' > ??????< intercept-url ?pattern ="/**" ?access ="ROLE_USER" ?/> ?? </ http > ??
<http auto-config='true'><intercept-url pattern="/**" access="ROLE_USER" />
</http>
這段配置表示:我們要保護應用程序中的所有URL,只有擁有ROLE_USER角色的用戶才能訪問。你可以使用多個<intercept-url>元素為不同URL的集合定義不同的訪問需求,它們會被歸入一個有序隊列中,每次取出最先匹配的一個元素使用。 所以你必須把期望使用的匹配條件放到最上邊。 3. 配置UserDetailsService來指定用戶和權限 接下來,我們來配置一個UserDetailsService來指定用戶和權限:
Xml代碼
< authentication-provider > ??????< user-service > ?? ??????< user ?name ="downpour" ?password ="downpour" ?authorities ="ROLE_USER,?ROLE_ADMIN" ?/> ?? ??????< user ?name ="robbin" ?password ="robbin" ?authorities ="ROLE_USER" ?/> ?? ??????< user ?name ="QuakeWang" ?password ="QuakeWang" ?authorities ="ROLE_ADMIN" ?/> ?? ????</ user-service > ?? ??</ authentication-provider > ??
<authentication-provider><user-service><user name="downpour" password="downpour" authorities="ROLE_USER, ROLE_ADMIN" /><user name="robbin" password="robbin" authorities="ROLE_USER" /><user name="QuakeWang" password="QuakeWang" authorities="ROLE_ADMIN" /></user-service></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代碼
< http > ??????< intercept-url ?pattern ="/**" ?access ="ROLE_USER" ?/> ?? ????< form-login ?/> ?? ????< anonymous ?/> ?? ????< http-basic ?/> ?? ????< logout ?/> ?? ????< remember-me ?/> ?? </ http > ??
<http><intercept-url pattern="/**" access="ROLE_USER" /><form-login /><anonymous /><http-basic /><logout /><remember-me />
</http>
這些元素分別與登錄認證,匿名認證,基本認證,注銷處理和remember-me對應。 他們擁有各自的屬性,可以改變他們的具體行為。 這樣,我們在Acegi中所熟悉的元素又浮現在我們的面前。只是在這里,我們使用的是命名空間而已。 2. 與Acegi的比較 我們仔細觀察一下沒有auto-config的那段XML配置,是不是熟悉多了?讓我們來將基于命名空間的配置與傳統的Acegi的bean的配置做一個比較,我們會發現以下的區別: 1) 基于命名空間的配置更加簡潔,可維護性更強 例如,基于命名空間進行登錄認證的配置代碼,可能像這樣:
Xml代碼
< form-login ?login-page ="/login.jsp" ?authentication-failure-url ="/login.jsp?error=true" ?default-target-url ="/work" ?/> ??
<form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/work" />
如果使用老的Acegi的Bean的定義方式,可能像這樣:
Xml代碼
< bean ?id ="authenticationProcessingFilter" ????????????class ="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter" > ?? ????< property ?name ="authenticationManager" ?? ??????????????????ref ="authenticationManager" /> ?? ????< property ?name ="authenticationFailureUrl" ?? ??????????????????value ="/login.jsp?error=1" /> ?? ????< property ?name ="defaultTargetUrl" ?value ="/work" /> ?? ????< property ?name ="filterProcessesUrl" ?? ??????????????????value ="/j_acegi_security_check" /> ?? ????< property ?name ="rememberMeServices" ?ref ="rememberMeServices" /> ?? </ bean > ??
<bean id="authenticationProcessingFilter"class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter"><property name="authenticationManager"ref="authenticationManager"/><property name="authenticationFailureUrl"value="/login.jsp?error=1"/><property name="defaultTargetUrl" value="/work"/><property name="filterProcessesUrl"value="/j_acegi_security_check"/><property name="rememberMeServices" ref="rememberMeServices"/>
</bean>
這樣的例子很多,有興趣的讀者可以一一進行比較。 2) 基于命名空間的配置,我們無需再擔心由于過濾器鏈的順序而導致的錯誤 以前,Acegi在缺乏默認內置配置的情況下,你需要自己來定義所有的bean,并指定這些bean在過濾器鏈中的順序。一旦順序錯了,很容易發生錯誤。而現在,過濾器鏈的順序被默認指定,你不需要在擔心由于順序的錯誤而導致的錯誤。 3. 過濾器鏈在哪里 到目前為止,我們都還沒有討論過整個Spring Security的核心部分:過濾器鏈。在原本Acegi的配置中,我們大概是這樣配置我們的過濾器鏈的:
Xml代碼
< bean ?id ="filterChainProxy" ????????????class ="org.acegisecurity.util.FilterChainProxy" > ?? ????< property ?name ="filterInvocationDefinitionSource" > ?? ????????< value > ?? ????????????????CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON ?? ????????????????PATTERN_TYPE_APACHE_ANT????????????????? ?? ????????????????/common/**=#NONE#? ?? ????????????????/css/**=#NONE#? ?? ????????????????/images/**=#NONE# ?? ????????????????/js/**=#NONE#? ?? ????????????????/login.jsp =#NONE# ?? ????????????????/**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,exceptionTranslationFilter,filterSecurityInterceptor ?? ????????</ value > ?? ????</ property > ?? </ bean > ??
<bean id="filterChainProxy"class="org.acegisecurity.util.FilterChainProxy"><property name="filterInvocationDefinitionSource"><value>CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISONPATTERN_TYPE_APACHE_ANT /common/**=#NONE# /css/**=#NONE# /images/**=#NONE#/js/**=#NONE# /login.jsp=#NONE#/**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,exceptionTranslationFilter,filterSecurityInterceptor</value></property>
</bean>
其中,每個過濾器鏈都將對應于Spring配置文件中的bean的id。 現在,在Spring Security中,我們將看不到這些配置,這些配置都被內置在<http>節點中。讓我們來看看這些默認的,已經被內置的過濾器: 這些過濾器已經被Spring容器默認內置注冊,這也就是我們不再需要在配置文件中定義那么多bean的原因。 同時,過濾器順序在使用命名空間的時候是被嚴格執行的。它們在初始化的時候就預先被排好序。不僅如此,Spring Security規定,你不能替換那些<http>元素自己使用而創建出的過濾器,比如HttpSessionContextIntegrationFilter, ExceptionTranslationFilter 或 FilterSecurityInterceptor 。 當然,這樣的規定是否合理,有待進一步討論。因為實際上在很多時候,我們希望覆蓋過濾器鏈中的某個過濾器的默認行為。而Spring Security的這種規定在一定程度上限制了我們的行為。 不過Spring Security允許你把你自己的過濾器添加到隊列中,使用custom-filter元素,并且指定你的過濾器應該出現的位置:
Xml代碼
< beans:bean ?id ="myFilter" ?class ="com.mycompany.MySpecialAuthenticationFilter" > ??????< custom-filter ?position ="AUTHENTICATION_PROCESSING_FILTER" /> ?? </ beans:bean > ??
<beans:bean id="myFilter" class="com.mycompany.MySpecialAuthenticationFilter"><custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/>
</beans:bean>
不僅如此,你還可以使用after或before屬性,如果你想把你的過濾器添加到隊列中另一個過濾器的前面或后面。 可以分別在position屬性使用"FIRST"或"LAST"來指定你想讓你的過濾器出現在隊列元素的前面或后面。 這個特性或許能夠在一定程度上彌補Spring Security的死板規定,而在之后的應用中,我也會把它作為切入點,對資源進行管理。 另外,我需要補充一點的是,對于在http/intercept-url中沒有進行定義的URL,將會默認使用系統內置的過濾器鏈進行權限認證。 所以,你并不需要在http/intercept-url中額外定義一個類似/**的匹配規則。 使用數據庫對用戶和權限進行管理 一般來說,我們都有使用數據庫對用戶和權限進行管理的需求,而不會把用戶寫死在配置文件里。所以,我們接下來就重點討論使用數據庫對用戶和權限進行管理的方法。 用戶和權限的關系設計 在此之前,我們首先需要討論一下用戶(User)和權限(Role)之間的關系。Spring Security在默認情況下,把這兩者當作一對多的關系進行處理。所以,在Spring Security中對這兩個對象所采用的表結構關系大概像這樣:
Java代碼
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 ?? );??
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代碼
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;??
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代碼
< authentication-provider > ??????< jdbc-user-service ?data-source-ref ="dataSource" ?? ????users-by-username-query ="SELECT?U.username,?U.password,?U.accountEnabled?AS?'enabled'?FROM?User?U?where?U.username=?" ?? ????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=?" /> ?? </ authentication-provider > ??
<authentication-provider><jdbc-user-service data-source-ref="dataSource"users-by-username-query="SELECT U.username, U.password, U.accountEnabled AS 'enabled' FROM User U where U.username=?"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=?"/>
</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代碼
public ?interface ?UserDetails?extends ?Serializable?{ ?????? ?? ????GrantedAuthority[]?getAuthorities(); ?? ?? ????String?getPassword(); ?? ?? ????String?getUsername(); ?? ?? ????boolean ?isAccountNonExpired(); ?? ?? ????boolean ?isAccountNonLocked(); ?? ?? ????boolean ?isCredentialsNonExpired(); ?? ?? ????boolean ?isEnabled(); ?? }??
public interface UserDetails extends Serializable {GrantedAuthority[] getAuthorities();String getPassword();String getUsername();boolean isAccountNonExpired();boolean isAccountNonLocked();boolean isCredentialsNonExpired();boolean isEnabled();
}
?
Java代碼
public ?interface ?UserDetailsService?{ ??????UserDetails?loadUserByUsername(String?username) ?? ????????throws ?UsernameNotFoundException,?DataAccessException; ?? }??
public interface UserDetailsService {UserDetails loadUserByUsername(String username)throws UsernameNotFoundException, DataAccessException;
}
非常清楚,一個接口用于模擬用戶,另外一個用于模擬讀取用戶的過程。所以我們可以通過實現這兩個接口,來完成使用數據庫對用戶和權限進行管理的需求。在這里,我將給出一個使用Hibernate來定義用戶和權限之間關系的示例。 1. 定義User類和Role類,使他們之間形成多對多的關系
Java代碼
@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; ?? ?? ?????????? }??
@Entity
@Proxy(lazy = false)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {private static final long serialVersionUID = 8026813053768023527L;@Id@GeneratedValueprivate 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代碼
@Entity ??@Cache (usage?=?CacheConcurrencyStrategy.READ_WRITE) ??public ?class ?Role?{ ?????? ?? ????@Id ?? ????@GeneratedValue ?? ????private ?Integer?id; ?? ???? ?? ????private ?String?name; ?? ???????? ?? ?????????? }??
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role {@Id@GeneratedValueprivate Integer id;private String name;// setters and getters
}
請注意這里的Annotation的寫法。同時,我為User和Role之間配置了緩存。并且將他們之間的關聯關系設置的lazy屬性設置成false,從而保證在User對象取出之后的使用不會因為脫離session的生命周期而產生lazy loading問題。 2. 使User類實現UserDetails接口 接下來,我們讓User類去實現UserDetails接口:
Java代碼
@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; ?? ???? ?? ????? ? ?? ????public ?User()?{ ?? ???????? ?? ????} ?? ?? ????? ? ?? ????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()]); ?? ????} ?? ?? ????? ? ?? ????public ?String?getPassword()?{ ?? ????????return ?password; ?? ????} ?? ?? ????? ? ?? ????public ?String?getUsername()?{ ?? ????????return ?name; ?? ????} ?? ?? ????? ? ?? ????public ?boolean ?isAccountNonExpired()?{ ?? ????????return ?true ; ?? ????} ?? ?? ????? ? ?? ????public ?boolean ?isAccountNonLocked()?{ ?? ????????return ?true ; ?? ????} ?? ?? ????? ? ?? ????public ?boolean ?isCredentialsNonExpired()?{ ?? ????????return ?true ; ?? ????} ?? ?? ????? ? ?? ????public ?boolean ?isEnabled()?{ ?? ????????return ?!this .disabled; ?? ????} ?? ?????? ?? ???????? }??
@Entity
@Proxy(lazy = false)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User implements UserDetails {private static final long serialVersionUID = 8026813053768023527L;@Id@GeneratedValueprivate 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代碼
? ? ?? 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#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代碼
< user ?name ="downpour" ?password ="downpour" ?authorities ="ROLE_USER,?ROLE_ADMIN" ?/> ??
<user name="downpour" password="downpour" authorities="ROLE_USER, ROLE_ADMIN" />
3. 實現UserDetailsService接口
Java代碼
@Repository ("securityManager" ) ??public ?class ?SecurityManagerSupport?extends ?HibernateDaoSupport?implements ?UserDetailsService?{ ???? ????? ? ? ? ?? ????@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 ); ?? ????} ?? }??
@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*/@Autowiredpublic 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代碼
< authentication-provider ?user-service-ref ="securityManager" > ??????< password-encoder ?hash ="md5" /> ?? </ authentication-provider > ??
<authentication-provider user-service-ref="securityManager"><password-encoder hash="md5"/>
</authentication-provider>
使用數據庫對資源進行管理 在完成了使用數據庫來進行用戶和權限的管理之后,我們再來看看http配置的部分。在實際應用中,我們不可能使用類似/**的方式來指定URL與權限ROLE的對應關系,而是會針對某些URL,指定某些特定的ROLE。而URL與ROLE之間的映射關系最好可以進行擴展和配置。而URL屬于資源的一種,所以接下來,我們就來看看如何使用數據庫來對權限和資源的匹配關系進行管理,并且將認證匹配加入到Spring Security中去。 權限和資源的設計 上面我們講到,用戶(User)和權限(Role)之間是一個多對多的關系。那么權限(Role)和資源(Resource)之間呢?其實他們之間也是一個典型的多對多的關系,我們同樣用3張表來表示:
Java代碼
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;??
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代碼
@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; ?? ?? ?????????? }??
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role {@Id@GeneratedValueprivate 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代碼
@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; ?? ???? ?? ????? ? ?? ????public ?Resource()?{ ?? ???????? ?? ????} ?? }??
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public class Resource {@Id@GeneratedValueprivate 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代碼
public ?class ?ServletContextLoaderListener?implements ?ServletContextListener?{ ???? ????? ? ?? ????public ?void ?contextInitialized(ServletContextEvent?servletContextEvent)?{ ?? ????????ServletContext?servletContext?=?servletContextEvent.getServletContext(); ?? ????????SecurityManager?securityManager?=?this .getSecurityManager(servletContext); ?? ???????? ?? ????????Map<String,?String>?urlAuthorities?=?securityManager.loadUrlAuthorities(); ?? ????????servletContext.setAttribute("urlAuthorities" ,?urlAuthorities); ?? ????} ?? ?? ???? ?? ????? ? ?? ????public ?void ?contextDestroyed(ServletContextEvent?servletContextEvent)?{ ?? ????????servletContextEvent.getServletContext().removeAttribute("urlAuthorities" ); ?? ????} ?? ?? ????? ? ? ? ? ?? ????protected ?SecurityManager?getSecurityManager(ServletContext?servletContext)?{ ?? ???????return ?(SecurityManager)?WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean("securityManager" );? ?? ????} ?? ?? }??
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代碼
@Service ("securityManager" ) ??public ?class ?SecurityManagerSupport?extends ?HibernateDaoSupport?implements ?UserDetailsService,?SecurityManager?{ ?????? ?? ????? ? ? ? ?? ????@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 ); ?? ????} ?? ???? ?? ????? ? ?? ????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; ?? ????}??? ?? }??
@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*/@Autowiredpublic 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代碼
public ?class ?SecureResourceFilterInvocationDefinitionSource?implements ?FilterInvocationDefinitionSource,?InitializingBean?{ ?????? ?? ????private ?UrlMatcher?urlMatcher; ?? ?? ????private ?boolean ?useAntPath?=?true ; ?? ???? ?? ????private ?boolean ?lowercaseComparisons?=?true ; ?? ???? ?? ????? ? ?? ????public ?void ?setUseAntPath(boolean ?useAntPath)?{ ?? ????????this .useAntPath?=?useAntPath; ?? ????} ?? ???? ?? ????? ? ?? ????public ?void ?setLowercaseComparisons(boolean ?lowercaseComparisons)?{ ?? ????????this .lowercaseComparisons?=?lowercaseComparisons; ?? ????} ?? ???? ?? ????? ? ?? ????public ?void ?afterPropertiesSet()?throws ?Exception?{ ?? ???????? ?? ?????????? ????????this .urlMatcher?=?new ?RegexUrlPathMatcher(); ?? ???????? ?? ????????if ?(useAntPath)?{???? ????????????this .urlMatcher?=?new ?AntUrlPathMatcher(); ?? ????????} ?? ???????? ?? ?????????? ????????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 ); ?? ????????????} ?? ????????} ?? ???????? ?? ????} ?? ???? ?? ????? ? ?? ????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 ; ?? ????} ?? ?? ????? ? ?? ????@SuppressWarnings ("unchecked" ) ?? ????public ?Collection?getConfigAttributeDefinitions()?{ ?? ????????return ?null ; ?? ????} ?? ?? ????? ? ?? ????@SuppressWarnings ("unchecked" ) ?? ????public ?boolean ?supports(Class?clazz)?{ ?? ????????return ?true ; ?? ????} ?? ???? ?? ????? ? ? ? ?? ????@SuppressWarnings ("unchecked" ) ?? ????private ?Map<String,?String>?getUrlAuthorities(FilterInvocation?filterInvocation)?{ ?? ????????ServletContext?servletContext?=?filterInvocation.getHttpRequest().getSession().getServletContext(); ?? ????????return ?(Map<String,?String>)servletContext.getAttribute("urlAuthorities" ); ?? ????} ?? ?? }??
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 RegexUrlPathMatcherthis.urlMatcher = new RegexUrlPathMatcher();if (useAntPath) { // change the implementation if requiredthis.urlMatcher = new AntUrlPathMatcher();}// Only change from the defaults if the attribute has been setif ("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代碼
< beans:beans ?xmlns ="http://www.springframework.org/schema/security" ??????xmlns:beans ="http://www.springframework.org/schema/beans" ?? ????xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" ?? ????xsi:schemaLocation ="http://www.springframework.org/schema/beans?http://www.springframework.org/schema/beans/spring-beans-2.5.xsd ?? ????????????????????????http://www.springframework.org/schema/security?http://www.springframework.org/schema/security/spring-security-2.0.4.xsd"> ?? ???? ?? ????< beans:bean ?id ="loggerListener" ?class ="org.springframework.security.event.authentication.LoggerListener" ?/> ?? ???? ?? ????< http ?access-denied-page ="/403.jsp" ?> ?? ????????< intercept-url ?pattern ="/static/**" ?filters ="none" ?/> ?? ????????< intercept-url ?pattern ="/template/**" ?filters ="none" ?/> ?? ????????< intercept-url ?pattern ="/" ?filters ="none" ?/> ?? ????????< intercept-url ?pattern ="/login.jsp" ?filters ="none" ?/> ?? ????????< form-login ?login-page ="/login.jsp" ?authentication-failure-url ="/login.jsp?error=true" ?default-target-url ="/index" ?/> ?? ????????< logout ?logout-success-url ="/login.jsp" /> ?? ????????< http-basic ?/> ?? ????</ http > ?? ?? ????< authentication-manager ?alias ="authenticationManager" /> ?? ???? ?? ????< authentication-provider ?user-service-ref ="securityManager" > ?? ????????< password-encoder ?hash ="md5" /> ?? ????</ authentication-provider > ?? ???? ?? ????< beans:bean ?id ="accessDecisionManager" ?class ="org.springframework.security.vote.AffirmativeBased" > ?? ????????< beans:property ?name ="allowIfAllAbstainDecisions" ?value ="false" /> ?? ????????< beans:property ?name ="decisionVoters" > ?? ????????????< beans:list > ?? ????????????????< beans:bean ?class ="org.springframework.security.vote.RoleVoter" /> ?? ????????????????< beans:bean ?class ="org.springframework.security.vote.AuthenticatedVoter" /> ?? ????????????</ beans:list > ?? ????????</ beans:property > ?? ????</ beans:bean > ?? ???? ?? ????< beans:bean ?id ="resourceSecurityInterceptor" ?class ="org.springframework.security.intercept.web.FilterSecurityInterceptor" > ?? ????????< beans:property ?name ="authenticationManager" ?ref ="authenticationManager" /> ?? ????????< beans:property ?name ="accessDecisionManager" ?ref ="accessDecisionManager" /> ?? ????????< beans:property ?name ="objectDefinitionSource" ?ref ="secureResourceFilterInvocationDefinitionSource" ?/> ?? ????????< beans:property ?name ="observeOncePerRequest" ?value ="false" ?/> ?? ????????< custom-filter ?after ="LAST" ?/> ?? ????</ beans:bean > ?? ???? ?? ????< beans:bean ?id ="secureResourceFilterInvocationDefinitionSource" ?class ="com.javaeye.sample.security.interceptor.SecureResourceFilterInvocationDefinitionSource" ?/> ?? ???? ?? </ beans:beans > ??
<beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd"><beans:bean id="loggerListener" class="org.springframework.security.event.authentication.LoggerListener" /><http access-denied-page="/403.jsp" ><intercept-url pattern="/static/**" filters="none" /><intercept-url pattern="/template/**" filters="none" /><intercept-url pattern="/" filters="none" /><intercept-url pattern="/login.jsp" filters="none" /><form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/index" /><logout logout-success-url="/login.jsp"/><http-basic /></http><authentication-manager alias="authenticationManager"/><authentication-provider user-service-ref="securityManager"><password-encoder hash="md5"/></authentication-provider><beans:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased"><beans:property name="allowIfAllAbstainDecisions" value="false"/><beans:property name="decisionVoters"><beans:list><beans:bean class="org.springframework.security.vote.RoleVoter"/><beans:bean class="org.springframework.security.vote.AuthenticatedVoter"/></beans:list></beans:property></beans:bean><beans:bean id="resourceSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor"><beans:property name="authenticationManager" ref="authenticationManager"/><beans:property name="accessDecisionManager" ref="accessDecisionManager"/><beans:property name="objectDefinitionSource" ref="secureResourceFilterInvocationDefinitionSource" /><beans:property name="observeOncePerRequest" value="false" /><custom-filter after="LAST" /></beans:bean><beans:bean id="secureResourceFilterInvocationDefinitionSource" class="com.javaeye.sample.security.interceptor.SecureResourceFilterInvocationDefinitionSource" /></beans:beans>
請注意,由于我們所實現的,是FilterSecurityInterceptor中的一個開放接口,所以我們實際上定義了一個新的bean,并通過<custom-filter after="LAST" />插入到過濾器鏈中去。 Spring Security對象的訪問 1. 訪問當前登錄用戶 Spring Security提供了一個線程安全的對象:SecurityContextHolder,通過這個對象,我們可以訪問當前的登錄用戶。我寫了一個類,可以通過靜態方法去讀取:
Java代碼
public ?class ?SecurityUserHolder?{ ???? ????? ? ? ? ?? ????public ?static ?User?getCurrentUser()?{ ?? ????????return ?(User)?SecurityContextHolder.getContext().getAuthentication().getPrincipal(); ?? ????} ?? ?? }??
public class SecurityUserHolder {/*** Returns the current user* * @return*/public static User getCurrentUser() {return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();}}
2. 訪問當前登錄用戶所擁有的權限 通過上面的分析,我們知道,用戶所擁有的所有權限,其實是通過UserDetails接口中的getAuthorities()方法獲得的。只要實現這個接口,就能實現需求。在我的代碼中,不僅實現了這個接口,還在上面做了點小文章,這樣我們可以獲得一個用戶所擁有權限的字符串表示:
Java代碼
? ? ?? 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()]); ?? } ?? ?? ? ? ? ? ? ? ? ? ?? public ?String?getAuthoritiesString()?{ ??????List<String>?authorities?=?new ?ArrayList<String>(); ?? ????for (GrantedAuthority?authority?:?this .getAuthorities())?{ ?? ????????authorities.add(authority.getAuthority()); ?? ????} ?? ????return ?StringUtils.join(authorities,?"," ); ?? }??
/* (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對象中實現了一個方法:
/*** @return the roleResources*/
public Map<String, List<Resource>> getRoleResources() {// init roleResources for the first timeif(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信息。 代碼示例 在附件中,我給出了一個簡單的例子,把我上面所講到的所有內容整合在一起,是一個eclipse的工程,大家可以下載進行參考。
SpringSecurity.zip (48.7 KB) 下載次數: 4717
總結
以上是生活随笔 為你收集整理的Spring Security 2 配置精讲 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。