眾所周知,Spring Security針對(duì)Acegi的一個(gè)重大的改進(jìn)就在于其配置方式大大簡(jiǎn)化了。所以如果配置還是基于Acegi-1.X這樣比較繁瑣的配置方式的話,那么我們還不如直接使用Acegi而不要去升級(jí)了。所以在這里,我將結(jié)合一個(gè)示例,重點(diǎn)討論一下Spring Security 2是如何進(jìn)行配置簡(jiǎn)化的。
搭建基礎(chǔ)環(huán)境
首先我們?yōu)槭纠罱ɑ镜拈_發(fā)環(huán)境,環(huán)境的搭建方式,可以參考我的另外一篇文章:http://www.javaeye.com/wiki/struts2/1321-struts2-development-environment-to-build
整個(gè)環(huán)境的搭建包括:創(chuàng)建合適的目錄結(jié)構(gòu)、加入了合適的Library,加入了基本的Jetty啟動(dòng)類、加入基本的配置文件等。最終的項(xiàng)目結(jié)構(gòu),可以參考我的附件。
參考文檔
這里主要的參考文檔是Spring Security的自帶的Reference。網(wǎng)絡(luò)上有一個(gè)它的中文翻譯,地址如下:http://www.family168.com/tutorial/springsecurity/html/springsecurity.html
除此之外,springside有一個(gè)比較完整的例子,不過(guò)是基于Acegi的,我也參閱了其中的一些實(shí)現(xiàn)。
Spring Security基本配置
Spring Security是基于Spring的的權(quán)限認(rèn)證框架,對(duì)于Spring和Acegi已經(jīng)比較熟悉的同學(xué)對(duì)于之前的配置方式應(yīng)該已經(jīng)非常了解。接下來(lái)的例子,將向大家展示Spring Security基于schema的配置方式。
最小化配置
1. 在web.xml文件中加入Filter聲明
- <!-- 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>
這個(gè)Filter會(huì)攔截所有的URL請(qǐng)求,并且對(duì)這些URL請(qǐng)求進(jìn)行Spring Security的驗(yàn)證。
注意,springSecurityFilterChain這個(gè)名稱是由命名空間默認(rèn)創(chuàng)建的用于處理web安全的一個(gè)內(nèi)部的bean的id。所以你在你的Spring配置文件中,不應(yīng)該再使用這個(gè)id作為你的bean。
與Acegi的配置不同,Acegi需要自行聲明一個(gè)Spring的bean來(lái)作為Filter的實(shí)現(xiàn),而使用Spring Security后,無(wú)需再額外定義bean,而是使用<http>元素進(jìn)行配置。
2. 使用最小的<http>配置
- <http auto-config='true'>
- <intercept-url pattern="/**" access="ROLE_USER" />
- </http>
這段配置表示:我們要保護(hù)應(yīng)用程序中的所有URL,只有擁有ROLE_USER角色的用戶才能訪問(wèn)。你可以使用多個(gè)<intercept-url>元素為不同URL的集合定義不同的訪問(wèn)需求,它們會(huì)被歸入一個(gè)有序隊(duì)列中,每次取出最先匹配的一個(gè)元素使用。 所以你必須把期望使用的匹配條件放到最上邊。
3. 配置UserDetailsService來(lái)指定用戶和權(quán)限
接下來(lái),我們來(lái)配置一個(gè)UserDetailsService來(lái)指定用戶和權(quán)限:
- <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的權(quán)限,robbin擁有ROLE_USER權(quán)限,QuakeWang擁有ROLE_ADMIN的權(quán)限
4. 小結(jié)
有了以上的配置,你已經(jīng)可以跑簡(jiǎn)單的Spring Security的應(yīng)用了。只不過(guò)在這里,我們還缺乏很多基本的元素,所以我們尚不能對(duì)上面的代碼進(jìn)行完整性測(cè)試。
如果你具備Acegi的知識(shí),你會(huì)發(fā)現(xiàn),有很多Acegi中的元素,在Spring Security中都沒(méi)有了,這些元素包括:表單和基本登錄選項(xiàng)、密碼編碼器、Remember-Me認(rèn)證等等。
接下來(lái),我們就來(lái)詳細(xì)剖析一下Spring Security中的這些基本元素。
剖析基本配置元素
1. 有關(guān)auto-config屬性
在上面用到的auto-config屬性,其實(shí)是下面這些配置的縮寫:
- <http>
- <intercept-url pattern="/**" access="ROLE_USER" />
- <form-login />
- <anonymous />
- <http-basic />
- <logout />
- <remember-me />
- </http>
這些元素分別與登錄認(rèn)證,匿名認(rèn)證,基本認(rèn)證,注銷處理和remember-me對(duì)應(yīng)。 他們擁有各自的屬性,可以改變他們的具體行為。
這樣,我們?cè)贏cegi中所熟悉的元素又浮現(xiàn)在我們的面前。只是在這里,我們使用的是命名空間而已。
2. 與Acegi的比較
我們仔細(xì)觀察一下沒(méi)有auto-config的那段XML配置,是不是熟悉多了?讓我們來(lái)將基于命名空間的配置與傳統(tǒng)的Acegi的bean的配置做一個(gè)比較,我們會(huì)發(fā)現(xiàn)以下的區(qū)別:
1) 基于命名空間的配置更加簡(jiǎn)潔,可維護(hù)性更強(qiáng)
例如,基于命名空間進(jìn)行登錄認(rèn)證的配置代碼,可能像這樣:
- <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/work" />
如果使用老的Acegi的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>
這樣的例子很多,有興趣的讀者可以一一進(jìn)行比較。
2) 基于命名空間的配置,我們無(wú)需再擔(dān)心由于過(guò)濾器鏈的順序而導(dǎo)致的錯(cuò)誤
以前,Acegi在缺乏默認(rèn)內(nèi)置配置的情況下,你需要自己來(lái)定義所有的bean,并指定這些bean在過(guò)濾器鏈中的順序。一旦順序錯(cuò)了,很容易發(fā)生錯(cuò)誤。而現(xiàn)在,過(guò)濾器鏈的順序被默認(rèn)指定,你不需要在擔(dān)心由于順序的錯(cuò)誤而導(dǎo)致的錯(cuò)誤。
3. 過(guò)濾器鏈在哪里
到目前為止,我們都還沒(méi)有討論過(guò)整個(gè)Spring Security的核心部分:過(guò)濾器鏈。在原本Acegi的配置中,我們大概是這樣配置我們的過(guò)濾器鏈的:
- <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>
其中,每個(gè)過(guò)濾器鏈都將對(duì)應(yīng)于Spring配置文件中的bean的id。
現(xiàn)在,在Spring Security中,我們將看不到這些配置,這些配置都被內(nèi)置在<http>節(jié)點(diǎn)中。讓我們來(lái)看看這些默認(rèn)的,已經(jīng)被內(nèi)置的過(guò)濾器:

這些過(guò)濾器已經(jīng)被Spring容器默認(rèn)內(nèi)置注冊(cè),這也就是我們不再需要在配置文件中定義那么多bean的原因。
同時(shí),過(guò)濾器順序在使用命名空間的時(shí)候是被嚴(yán)格執(zhí)行的。它們?cè)诔跏蓟臅r(shí)候就預(yù)先被排好序。不僅如此,Spring Security規(guī)定,你不能替換那些<http>元素自己使用而創(chuàng)建出的過(guò)濾器,比如HttpSessionContextIntegrationFilter, ExceptionTranslationFilter 或 FilterSecurityInterceptor。
當(dāng)然,這樣的規(guī)定是否合理,有待進(jìn)一步討論。因?yàn)閷?shí)際上在很多時(shí)候,我們希望覆蓋過(guò)濾器鏈中的某個(gè)過(guò)濾器的默認(rèn)行為。而Spring Security的這種規(guī)定在一定程度上限制了我們的行為。
不過(guò)Spring Security允許你把你自己的過(guò)濾器添加到隊(duì)列中,使用custom-filter元素,并且指定你的過(guò)濾器應(yīng)該出現(xiàn)的位置:
- <beans:bean id="myFilter" class="com.mycompany.MySpecialAuthenticationFilter">
- <custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/>
- </beans:bean>
不僅如此,你還可以使用after或before屬性,如果你想把你的過(guò)濾器添加到隊(duì)列中另一個(gè)過(guò)濾器的前面或后面。 可以分別在position屬性使用"FIRST"或"LAST"來(lái)指定你想讓你的過(guò)濾器出現(xiàn)在隊(duì)列元素的前面或后面。
這個(gè)特性或許能夠在一定程度上彌補(bǔ)Spring Security的死板規(guī)定,而在之后的應(yīng)用中,我也會(huì)把它作為切入點(diǎn),對(duì)資源進(jìn)行管理。
另外,我需要補(bǔ)充一點(diǎn)的是,對(duì)于在http/intercept-url中沒(méi)有進(jìn)行定義的URL,將會(huì)默認(rèn)使用系統(tǒng)內(nèi)置的過(guò)濾器鏈進(jìn)行權(quán)限認(rèn)證。所以,你并不需要在http/intercept-url中額外定義一個(gè)類似/**的匹配規(guī)則。
使用數(shù)據(jù)庫(kù)對(duì)用戶和權(quán)限進(jìn)行管理
一般來(lái)說(shuō),我們都有使用數(shù)據(jù)庫(kù)對(duì)用戶和權(quán)限進(jìn)行管理的需求,而不會(huì)把用戶寫死在配置文件里。所以,我們接下來(lái)就重點(diǎn)討論使用數(shù)據(jù)庫(kù)對(duì)用戶和權(quán)限進(jìn)行管理的方法。
用戶和權(quán)限的關(guān)系設(shè)計(jì)
在此之前,我們首先需要討論一下用戶(User)和權(quán)限(Role)之間的關(guān)系。Spring Security在默認(rèn)情況下,把這兩者當(dāng)作一對(duì)多的關(guān)系進(jìn)行處理。所以,在Spring Security中對(duì)這兩個(gè)對(duì)象所采用的表結(jié)構(gòu)關(guān)系大概像這樣:
- 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
- );
不過(guò)這種設(shè)計(jì)方式在實(shí)際生產(chǎn)環(huán)境中基本上不會(huì)采用。一般來(lái)說(shuō),我們會(huì)使用邏輯主鍵ID來(lái)標(biāo)示每個(gè)User和每個(gè)Authorities(Role)。而且從典型意義上講,他們之間是一個(gè)多對(duì)多的關(guān)系,我們會(huì)采用3張表來(lái)表示,下面是我在MySQL中建立的3張表的schema示例:
- 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;
通過(guò)配置SQL來(lái)模擬用戶和權(quán)限
有了數(shù)據(jù)庫(kù)的表設(shè)計(jì),我們就可以在Spring Security中,通過(guò)配置SQL,來(lái)模擬用戶和權(quán)限,這依然通過(guò)<authentication-provider>來(lái)完成:
- <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>
這里給出的是一個(gè)使用SQL進(jìn)行模擬用戶和權(quán)限的示例。其中你需要為運(yùn)行SQL準(zhǔn)備相應(yīng)的dataSource。這個(gè)dataSource應(yīng)該對(duì)應(yīng)于Spring中的某個(gè)bean的定義。
從這段配置模擬用戶和權(quán)限的情況來(lái)看,實(shí)際上Spring Security對(duì)于用戶,需要username,password,accountEnabled三個(gè)字段。對(duì)于權(quán)限,它需要的是username和authority2個(gè)字段。
也就是說(shuō),如果我們能夠通過(guò)其他的方式,模擬上面的這些對(duì)象,并插入到Spring Security中去,我們同樣能夠?qū)崿F(xiàn)用戶和權(quán)限的認(rèn)證。接下來(lái),我們就來(lái)看看我們?nèi)绾瓮ㄟ^(guò)自己的實(shí)現(xiàn),來(lái)完成這件事情。
通過(guò)擴(kuò)展Spring Security的默認(rèn)實(shí)現(xiàn)來(lái)進(jìn)行用戶和權(quán)限的管理
事實(shí)上,Spring Security提供了2個(gè)認(rèn)證的接口,分別用于模擬用戶和權(quán)限,以及讀取用戶和權(quán)限的操作方法。這兩個(gè)接口分別是:UserDetails和UserDetailsService。
- public interface UserDetails extends Serializable {
- GrantedAuthority[] getAuthorities();
- String getPassword();
- String getUsername();
- boolean isAccountNonExpired();
- boolean isAccountNonLocked();
- boolean isCredentialsNonExpired();
- boolean isEnabled();
- }
- public interface UserDetailsService {
- UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException, DataAccessException;
- }
非常清楚,一個(gè)接口用于模擬用戶,另外一個(gè)用于模擬讀取用戶的過(guò)程。所以我們可以通過(guò)實(shí)現(xiàn)這兩個(gè)接口,來(lái)完成使用數(shù)據(jù)庫(kù)對(duì)用戶和權(quán)限進(jìn)行管理的需求。在這里,我將給出一個(gè)使用Hibernate來(lái)定義用戶和權(quán)限之間關(guān)系的示例。
1. 定義User類和Role類,使他們之間形成多對(duì)多的關(guān)系
- @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
- }
- @Entity
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public class Role {
- @Id
- @GeneratedValue
- private Integer id;
- private String name;
- // setters and getters
- }
請(qǐng)注意這里的Annotation的寫法。同時(shí),我為User和Role之間配置了緩存。并且將他們之間的關(guān)聯(lián)關(guān)系設(shè)置的lazy屬性設(shè)置成false,從而保證在User對(duì)象取出之后的使用不會(huì)因?yàn)槊撾xsession的生命周期而產(chǎn)生lazy loading問(wèn)題。
2. 使User類實(shí)現(xiàn)UserDetails接口
接下來(lái),我們讓User類去實(shí)現(xiàn)UserDetails接口:
- @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
- }
實(shí)現(xiàn)UserDetails接口中的每個(gè)函數(shù),其實(shí)沒(méi)什么很大的難度,除了其中的一個(gè)函數(shù)我需要額外強(qiáng)調(diào)一下:
- /* (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()]);
- }
這個(gè)函數(shù)的實(shí)際作用是根據(jù)User返回這個(gè)User所擁有的權(quán)限列表。如果以上面曾經(jīng)用過(guò)的例子來(lái)說(shuō),如果當(dāng)前User是downpour,我需要得到ROLE_USER和ROLE_ADMIN;如果當(dāng)前User是robbin,我需要得到ROLE_USER。
了解了含義,實(shí)現(xiàn)就變得簡(jiǎn)單了,由于User與Role是多對(duì)多的關(guān)系,我們可以通過(guò)User得到所有這個(gè)User所對(duì)應(yīng)的Role,并把這些Role的name拼裝起來(lái)返回。
由此可見(jiàn),實(shí)現(xiàn)UserDetails接口,并沒(méi)有什么神秘的地方,它只是實(shí)際上在一定程度上只是代替了使用配置文件的硬編碼:
- <user name="downpour" password="downpour" authorities="ROLE_USER, ROLE_ADMIN" />
3. 實(shí)現(xiàn)UserDetailsService接口
- @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);
- }
- }
這個(gè)實(shí)現(xiàn)非常簡(jiǎn)單,由于我們的User對(duì)象已經(jīng)實(shí)現(xiàn)了UserDetails接口。所以我們只要使用Hibernate,根據(jù)userName取出相應(yīng)的User對(duì)象即可。注意在這里,由于我們對(duì)于User的關(guān)聯(lián)對(duì)象Roles都設(shè)置了lazy="false",所以我們無(wú)需擔(dān)心lazy loading的問(wèn)題。
4. 配置文件
有了上面的代碼,一切都變得很簡(jiǎn)單,重新定義authentication-provider節(jié)點(diǎn)即可。如果你使用Spring 2.5的Annotation配置功能,你甚至可以不需要在配置文件中定義securityManager的bean。
- <authentication-provider user-service-ref="securityManager">
- <password-encoder hash="md5"/>
- </authentication-provider>
使用數(shù)據(jù)庫(kù)對(duì)資源進(jìn)行管理
在完成了使用數(shù)據(jù)庫(kù)來(lái)進(jìn)行用戶和權(quán)限的管理之后,我們?cè)賮?lái)看看http配置的部分。在實(shí)際應(yīng)用中,我們不可能使用類似/**的方式來(lái)指定URL與權(quán)限ROLE的對(duì)應(yīng)關(guān)系,而是會(huì)針對(duì)某些URL,指定某些特定的ROLE。而URL與ROLE之間的映射關(guān)系最好可以進(jìn)行擴(kuò)展和配置。而URL屬于資源的一種,所以接下來(lái),我們就來(lái)看看如何使用數(shù)據(jù)庫(kù)來(lái)對(duì)權(quán)限和資源的匹配關(guān)系進(jìn)行管理,并且將認(rèn)證匹配加入到Spring Security中去。
權(quán)限和資源的設(shè)計(jì)
上面我們講到,用戶(User)和權(quán)限(Role)之間是一個(gè)多對(duì)多的關(guān)系。那么權(quán)限(Role)和資源(Resource)之間呢?其實(shí)他們之間也是一個(gè)典型的多對(duì)多的關(guān)系,我們同樣用3張表來(lái)表示:
- 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等等。
針對(duì)資源的認(rèn)證
針對(duì)資源的認(rèn)證,實(shí)際上應(yīng)該由Spring Security中的FilterSecurityInterceptor這個(gè)過(guò)濾器來(lái)完成。不過(guò)內(nèi)置的FilterSecurityInterceptor的實(shí)現(xiàn)往往無(wú)法滿足我們的要求,所以傳統(tǒng)的Acegi的方式,我們往往會(huì)替換FilterSecurityInterceptor的實(shí)現(xiàn),從而對(duì)URL等資源進(jìn)行認(rèn)證。
不過(guò)在Spring Security中,由于默認(rèn)的攔截器鏈內(nèi)置了FilterSecurityInterceptor,而且上面我們也提到過(guò),這個(gè)實(shí)現(xiàn)無(wú)法被替換。這就使我們犯了難。我們?nèi)绾螌?duì)資源進(jìn)行認(rèn)證呢?
實(shí)際上,我們雖然無(wú)法替換FilterSecurityInterceptor的默認(rèn)實(shí)現(xiàn),不過(guò)我們可以再實(shí)現(xiàn)一個(gè)類似的過(guò)濾器,并將我們自己的過(guò)濾器作為一個(gè)customer-filter,加到默認(rèn)的過(guò)濾器鏈的最后,從而完成整個(gè)過(guò)濾檢查。
接下來(lái)我們就來(lái)看看一個(gè)完整的例子:
1. 建立權(quán)限(Role)和資源(Resource)之間的關(guān)聯(lián)關(guān)系
修改上面的權(quán)限(Role)的Entity定義:
- @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定義:
- @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() {
- }
- }
注意他們之間的多對(duì)多關(guān)系,以及他們之間關(guān)聯(lián)關(guān)系的緩存和lazy屬性設(shè)置。
2. 在系統(tǒng)啟動(dòng)的時(shí)候,把所有的資源load到內(nèi)存作為緩存
由于資源信息對(duì)于每個(gè)項(xiàng)目來(lái)說(shuō),相對(duì)固定,所以我們可以將他們?cè)谙到y(tǒng)啟動(dòng)的時(shí)候就load到內(nèi)存作為緩存。這里做法很多,我給出的示例是將資源的存放在servletContext中。
- 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,這是一個(gè)接口,用于權(quán)限相關(guān)的邏輯處理。還記得之前我們使用數(shù)據(jù)庫(kù)管理User的時(shí)候所使用的一個(gè)實(shí)現(xiàn)類SecurityManagerSupport嘛?我們不妨依然借用這個(gè)類,讓它實(shí)現(xiàn)SecurityManager接口,來(lái)同時(shí)完成url的讀取工作。
- @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實(shí)現(xiàn)類,對(duì)資源進(jìn)行認(rèn)證
- 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. 配置文件修改
接下來(lái),我們來(lái)修改一下Spring Security的配置文件,把我們自定義的這個(gè)過(guò)濾器插入到過(guò)濾器鏈中去。
- <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>
請(qǐng)注意,由于我們所實(shí)現(xiàn)的,是FilterSecurityInterceptor中的一個(gè)開放接口,所以我們實(shí)際上定義了一個(gè)新的bean,并通過(guò)<custom-filter after="LAST" />插入到過(guò)濾器鏈中去。
Spring Security對(duì)象的訪問(wèn)
1. 訪問(wèn)當(dāng)前登錄用戶
Spring Security提供了一個(gè)線程安全的對(duì)象:SecurityContextHolder,通過(guò)這個(gè)對(duì)象,我們可以訪問(wèn)當(dāng)前的登錄用戶。我寫了一個(gè)類,可以通過(guò)靜態(tài)方法去讀取:
- public class SecurityUserHolder {
- /**
- * Returns the current user
- *
- * @return
- */
- public static User getCurrentUser() {
- return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- }
- }
2. 訪問(wèn)當(dāng)前登錄用戶所擁有的權(quán)限
通過(guò)上面的分析,我們知道,用戶所擁有的所有權(quán)限,其實(shí)是通過(guò)UserDetails接口中的getAuthorities()方法獲得的。只要實(shí)現(xiàn)這個(gè)接口,就能實(shí)現(xiàn)需求。在我的代碼中,不僅實(shí)現(xiàn)了這個(gè)接口,還在上面做了點(diǎn)小文章,這樣我們可以獲得一個(gè)用戶所擁有權(quán)限的字符串表示:
- /* (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. 訪問(wèn)當(dāng)前登錄用戶能夠訪問(wèn)的資源
這就涉及到用戶(User),權(quán)限(Role)和資源(Resource)三者之間的對(duì)應(yīng)關(guān)系。我同樣在User對(duì)象中實(shí)現(xiàn)了一個(gè)方法:
- /**
- * @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;
- }
這里,會(huì)在User對(duì)象中設(shè)置一個(gè)緩存機(jī)制,在第一次取的時(shí)候,通過(guò)遍歷User所有的Role,獲取相應(yīng)的Resource信息