`
lijuanabc
  • 浏览: 119899 次
社区版块
存档分类
最新评论

Spring Security3 十五日研究

 
阅读更多
前言

南朝《述异记》中记载,晋王质上山砍柴,见二童子下棋,未看完,斧柄已烂,下山回村,闻同代人都去世了,自已还未变老。
因此发出“山中方一日,世上几千年” 的慨叹。原文寥寥几笔,读来却发人深省。

另有宋朝周敦颐在《暮春即事》中也有诗云:双双瓦雀行书案,点点杨花入砚池。闲坐小窗读周易,不知春去几多时。

上述古文或古诗中对于时间的论述最符合我现在的感受。已经整整十五日,对于Spring Serurity3的研究终于可以告一个段落了。

感觉这过往的十五日仿佛一瞬间而过,我沉浸在此中,一种强烈的求知愿望使我乐此不疲。到今天为止,终于将一种版本调通,可以正常使用了。
再回头看时,楼下的小公园里已经开放了一丛丛黄色的花朵,整齐的柳树丛林里,已被春风剪出嫩绿的风景。
再回头看自己其间的经历,有几多所得做为铺垫,所有的痛苦和疲惫已经烟消云散了。
欣喜之余整理一下,一来梳理一下自己的认知,进一步深入的理解;二来可以记录下来作为参考。

使用Spring Security3的四种方法概述

那么在Spring Security3的使用中,有4种方法:

一种是全部利用配置文件,将用户、权限、资源(url)硬编码在xml文件中,已经实现过,并经过验证;

二种是用户和权限用数据库存储,而资源(url)和权限的对应采用硬编码配置,目前这种方式已经实现,并经过验证。

三种是细分角色和权限,并将用户、角色、权限和资源均采用数据库存储,并且自定义过滤器,代替原有的FilterSecurityInterceptor过滤器,
并分别实现AccessDecisionManager、InvocationSecurityMetadataSourceService和UserDetailsService,并在配置文件中进行相应配置。
目前这种方式已经实现,并经过验证。

四是修改spring security的源代码,主要是修改InvocationSecurityMetadataSourceService和UserDetailsService两个类。
前者是将配置文件或数据库中存储的资源(url)提取出来加工成为url和权限列表的Map供Security使用,后者提取用户名和权限组成一个完整的(UserDetails)User对象,该对象可以提供用户的详细信息供AuthentationManager进行认证与授权使用。
该方法理论上可行,但是比较暴力,也没有时间实现,未验证,以后再研究。

说明一下,我目前调通的环境为: java1.6 + struts2.1.6 + spring3.0.1 + hibernate3.3.1 + spring security3.0.2 + oracle9i + weblogic10.3,
顺便提一下,目前(2011-4-2)serutity的最新版本为3.1,比较稳定的版本为3.0.5和2.0.6。

当然在进行spring security3的下面4种方法介绍之前,先假定SSH2的环境已经配置完毕,进入正常开发的过程,并且已经导入
spring security3.0.2的5个jar包,分别为:
spring-security-acl-3.0.2.RELEASE.jar
spring-security-config-3.0.2.RELEASE.jar
spring-security-core-3.0.2.RELEASE.jar
spring-security-taglibs-3.0.2.RELEASE.jar
spring-security-web-3.0.2.RELEASE.jar
当然还有其他相关的jar包,在此不再赘述。


第一种方法

第一种方法比较简单,可参考Spring Security自带的例子spring-security-samples-tutorial-3.0.2.RELEASE。
这里给出下载网址:http://www.springsource.com/download/community?sid=1087087,不过在下载之前必须填写相应的用户信息,才允许下载。各种版本号的均可以下载。

在spring-security-samples-tutorial-3.0.2.RELEASE的例子里,硬编码的配置请参见applicationContext-security.xml文件中的内容。
里面配置了用户名、经过MD5加密后的密码密文、相关的权限,以及与权相对应的访问资源(URL)。还有对于Session超时时的处理。
特别是因为版本号为3.0.2,因此还增加了对表达式的配置演示,具体内容请参见该例子。

当然你最好运行起该例子来,感受一下,你可以直接将下载下来的解压缩后的文件夹中找到spring-security-samples-tutorial-3.0.2.RELEASE.war文件,然后拷贝到Tomcat的安装目录下的\webapps文件夹下,然后运行Tomcat的服务器,服务器在启动过程中,会自动解开该war文件,在IE内输入http://localhost:8080/webapps/spring-security-samples-tutorial-3.0.2.RELEASE 就可以运行该系统了。在此不再赘述。

第二种方法

第二种方法的代码如下:

使用到的两个表,用户表和权限表的SQL语句。将用户和权限以数据库进行存储。

createtableUSERS(
USERNAME
VARCHAR2(50)notnull,
PASSWORD
VARCHAR2(50)notnull,
ENABLED
NUMBER(1)notnull,
USERNAMECN
VARCHAR2(50),
primarykey(username)
)

createtableAUTHORITIES(
USERNAME
VARCHAR2(50)notnull,
AUTHORITY
VARCHAR2(50)notnull
)

-- 外键使用户和权限相联。

Create/Recreateprimary,uniqueandforeignkeyconstraints
altertableAUTHORITIES
addconstraintFK_AUTHORITIES_USERSforeignkey(USERNAME)
referencesUSERS(USERNAME);


可插入几条数据做为试验,首先插入用户:

insertintousers(USERNAME,PASSWORD,ENABLED,USERNAMECN,ROWID)
values('lxb','c7d3f4c857bc8c145d6e5d40c1bf23d9',1,'登录用户','AAAHmhAALAAAAAOAAA');

insertintousers(USERNAME,PASSWORD,ENABLED,USERNAMECN,ROWID)
values('admin','ceb4f32325eda6142bd65215f4c0f371',1,'系统管理员','AAAHmhAALAAAAAPAAA');

insertintousers(USERNAME,PASSWORD,ENABLED,USERNAMECN,ROWID)
values('user','47a733d60998c719cf3526ae7d106d13',1,'普通用户','AAAHmhAALAAAAAPAAB');

再插入角色:

insertintoauthorities(USERNAME,AUTHORITY,ROWID)
values('admin','ROLE_PLATFORMADMIN','AAAHmjAALAAAAAgAAA');

insertintoauthorities(USERNAME,AUTHORITY,ROWID)
values('admin','ROLE_SYSADMIN','AAAHmjAALAAAAAgAAB');

insertintoauthorities(USERNAME,AUTHORITY,ROWID)
values('lxb','ROLE_LOGIN','AAAHmjAALAAAAAeAAA');

insertintoauthorities(USERNAME,AUTHORITY,ROWID)
values('lxb','ROLE_LOGINTOWELCOME','AAAHmjAALAAAAAeAAB');

insertintoauthorities(USERNAME,AUTHORITY,ROWID)
values('user','ROLE_USER','AAAHmjAALAAAAAgAAC');


第二种方法之密码加密

可能要有人要问,用户表里面的密码是如何取得的呢?这个密码是通过MD5进行加密过的,并且以用户名做为了盐值,最后就成为32位数字这个样子,这个你可以参见下面applicationContext-Security.xml中的password-encoder和salt-source的配置就会明白。
那么在spring security3中是如何加密的呢?当我们设置了pawwrod-encoder和salt-source之后,Spring Security3会根据配置,采用相匹配的加密算法(比如设置了MD5加密算法)再加上salt-source进行加密,形成32位数字的密文。
比如用户名为yew,密码为yew1234,盐值为用户名yew。那么最后加密的明文为“yew1234{yew}”,密文就为“8fe2657d1599dba8e78a7a0bda8651bb”。

我们在试验过程中,通常喜欢先将几个常用的用户及密码插入数据库进行试验,这种情况下如何得到该用户的密码密文呢?
不妨试试我这个办法,假设,用户名为user,密码明文为user369,而且在配置文件里面设置了以MD5作为加密算法,并以用户名做为盐值。
那么你可以首先将各个信息组合成待加密的密码明文, 应是 密码明文 + { + 盐值 + }, 那么很明显,上述user的密码明文应当是:

user369{user}

拿上述的字串拷贝到 http://www.51240.com/md5jiami/ 网页上的输入框里,点击加密按钮,下面即可生成32位数字的密码密文。

哈哈,屡试不爽啊。这个方法要谨慎使用,一般人我不告诉他。


第二种方法之相关配置

将权限及资源(URL或Action)的关系配置在xml文件中,并且配置与Spring Security3相关的其他配置:

1、applicationContext-Security.xml代码:

<b:beansxmlns="http://www.springframework.org/schema/security"
xmlns:b
="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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd"
>

<httpauto-config="true"access-denied-page="/accessDenied.jsp">
<!--不要过滤图片等静态资源,其中**代表可以跨越目录,*不可以跨越目录。-->
<intercept-urlpattern="/**/*.jpg"filters="none"/>
<intercept-urlpattern="/**/*.png"filters="none"/>
<intercept-urlpattern="/**/*.gif"filters="none"/>
<intercept-urlpattern="/**/*.css"filters="none"/>
<intercept-urlpattern="/**/*.js"filters="none"/>
<!--登录页面和忘记密码页面不过滤-->
<intercept-urlpattern="/login.jsp"filters="none"/>
<intercept-urlpattern="/jsp/forgotpassword.jsp"filters="none"/>

<!--下面是对Action配置。表示具有访问/unitsManager资源的用户必须具有ROLE_PLATFORMADMIN的权限。
当用户登录时,SS3将用户的所有权限从数据库中提取出来,形成列表。当用户访问该资源时,SS3将
登录用户的权限列表提出来跟下面配置的权限进行比对,若有,则允许访问,若没有,则给出AccessDeniedException。
-->
<intercept-urlpattern="/unitsManager"access="ROLE_PLATFORMADMIN"/>
<intercept-urlpattern="/usersManager" access="ROLE_PLATFORMADMIN"/>

<intercept-urlpattern="/horizontalQuery"access="ROLE_PLATFORMADMIN"/>

<intercept-urlpattern="/verticalQuery"access="ROLE_PLATFORMADMIN"/>

<form-loginlogin-page="/login.jsp"authentication-failure-url="/login.jsp?error=true"default-target-url="/index.jsp"/>

<!--"记住我"功能,采用持久化策略(将用户的登录信息存放在数据库表中)-->
<remember-medata-source-ref="dataSource"/>

<!--检测失效的sessionId,超时时定位到另外一个URL-->
<session-managementinvalid-session-url="/sessionTimeout.jsp"/>

</http>

<!--注意能够为authentication-manager设置alias别名-->
<authentication-manageralias="authenticationManager">
<authentication-provideruser-service-ref="userDetailsManager">
<password-encoderref="passwordEncoder">
<!--用户名做为盐值-->
<salt-sourceuser-property="username"/>
</password-encoder>
</authentication-provider>
</authentication-manager>

</b:beans>

2、applicationContext.service.xml:

<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util
="http://www.springframework.org/schema/util"
xmlns:jee
="http://www.springframework.org/schema/jee"
xmlns:aop
="http://www.springframework.org/schema/aop"
xmlns:tx
="http://www.springframework.org/schema/tx"
xmlns:context
="http://www.springframework.org/schema/context"
xsi:schemaLocation
="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd"
>

<!--定义上下文返回的消息的国际化。-->
<beanid="messageSource"
class
="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<propertyname="basename"
value
="classpath:org/springframework/security/messages_zh_CN"/>
</bean>

<!--事件监听:实现了ApplicationListener监听接口,包括AuthenticationCredentialsNotFoundEvent事件,
AuthorizationFailureEvent事件,AuthorizedEvent事件,PublicInvocationEvent事件
-->
<beanclass="org.springframework.security.authentication.event.LoggerListener"/>

<!--用户的密码加密或解密-->
<beanid="passwordEncoder"
class
="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>


<!--用户详细信息管理:数据源、用户缓存、启用用户组功能。-->
<beanid="userDetailsManager"
class
="org.springframework.security.provisioning.JdbcUserDetailsManager">
<propertyname="dataSource"ref="dataSource"/>
<propertyname="userCache"ref="userCache"/>
</bean>

<beanid="userCache"
class
="org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache">
<propertyname="cache"ref="userEhCache"/>
</bean>


<beanid="userEhCache"class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<propertyname="cacheName"value="userCache"/>
<propertyname="cacheManager"ref="cacheManager"/>
</bean>

<!--缓存用户管理-->
<beanid="cacheManager"
class
="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>


<!--springsecurity自带的与权限有关的数据读写Jdbc模板-->
<beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">
<propertyname="dataSource"ref="dataSource"/>
</bean>

</beans>

3、web.xml:

<web-appversion="2.5"xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation
="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
>


<!--设置log4j存放Log文件位置(通过spring统一进行管理)-->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>log.root</param-value>
</context-param>

<!--加载log4j的配置文件-->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/log4j.properties</param-value>
</context-param>

<!--Spring默认刷新Log4j配置文件的间隔,单位为millisecond-->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>

<!--Spring用于log4j初始化的监听器-->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

<!--
加载SpringXML配置文件,Spring安全配置及各类资源文件,暂不加
/WEB-INF/applicationContext-security.xml,
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext*.xml,
classpath*:applicationContext.xml
</param-value>
</context-param>

<!--spring监听器的配置,用于在启动Web容器时,自动装配ApplicationContext的配置信息-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!--使用Spring中的过滤器解决在请求和应答中的中文乱码问题-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gbk</param-value>
</init-param>
<init-param>
<!--强制转换编码(request和response均适用)-->
<param-name>ForceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<!--SpringSecutiry3.0.2的过滤器链配置-->
<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>


<!--配置Struts2的FilterDispathcer的Filter-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>

<!--struts2用以处理用户Web请求的路径模式-->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



<!--避免乱码问题-->
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!--Spring刷新Interceptor防止内存泄漏-->
<listener>
<listener-class>
org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>


<!--设置session超时时间为20分钟-->
<session-config>
<session-timeout>20</session-timeout>
</session-config>

<!--系统欢迎页面-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

</web-app>


令人欣喜的是,整个Security配置过程中,除了建立数据库和编写配置文件之外,不需要编写任何的代码。怎么样? 有点意思吧!

第二种方法中遇见的问题

当然,首次使用Spring serutiry,在整合的过程中,我还是遇见了不少问题,当然有些问题比如找不到类呀,包呀,和框架的整合呀等问题不作为谈论的重点。主要还是探讨Spring Security的配置和注意事项的问题。

我在其中碰到的对我印象最深的问题是,当完全配置好之后,重启Web服务器,却发现Spring Security不能拦截任何的URL了,这使我感到惊诧,因为在去年时,我已经将该框架搭建完成,在当时正是使用的该种方法,并且在试验是否能够拦截jsp文件时进行了确认是没有问题的。

接下来我又整理了一下applicationContext-security.xml的文件才发现, 除了不需要进行检测的图片及登录页面之外,没有对任何的资源和权限之间的对应关系进行配置,参见下面的代码:

<httpauto-config="true"access-denied-page="/accessDenied.jsp">
<!--不要过滤图片等静态资源,其中**代表可以跨越目录,*不可以跨越目录。-->
<intercept-urlpattern="/**/*.jpg"filters="none"/>
<intercept-urlpattern="/**/*.png"filters="none"/>
<intercept-urlpattern="/**/*.gif"filters="none"/>
<intercept-urlpattern="/**/*.css"filters="none"/>
<intercept-urlpattern="/**/*.js"filters="none"/>
<!--登录页面和忘记密码页面不过滤-->
<intercept-urlpattern="/login.jsp"filters="none"/>
<intercept-urlpattern="/jsp/forgotpassword.jsp"filters="none"/>

<!--下面是对Struts2的Action请求时的配置。注意在前面加/,否则不会被SS3进行拦截验证。
表示具有访问/unitsManager资源的用户必须具有ROLE_PLATFORMADMIN的权限。
当用户登录时,SS3将用户的所有权限从数据库中提取出来,形成列表。当用户访问该资源时,
SS3将登录用户的权限列表提出来跟下面配置的权限进行比对,若有,则允许访问,若没有,
则给出AccessDeniedException。
<intercept-urlpattern="/unitsManager"access="ROLE_PLATFORMADMIN"/>
<intercept-urlpattern="/usersManager"access="ROLE_PLATFORMADMIN"/>
<intercept-urlpattern="/horizontalQuery"access="ROLE_PLATFORMADMIN"/>
<intercept-urlpattern="/verticalQuery"access="ROLE_PLATFORMADMIN"/>
-->

<form-loginlogin-page="/login.jsp"
authentication-failure-url
="/login.jsp?error=true"
default-target-url
="/index.jsp"/>

<!--"记住我"功能,采用持久化策略(将用户的登录信息存放在数据库表中)-->
<remember-medata-source-ref="dataSource"/>

<!--检测失效的sessionId,超时时定位到另外一个URL-->
<session-managementinvalid-session-url="/sessionTimeout.jsp"/>

</http>

这样一来,spring security3就会认为根本不需要对任何的URL或Action进行检测(注意上面代码中被注释掉的4条配置)。 哈哈,当时这个问题深深动摇了我对Spring security的信心,花费了这么多天的精力,却是这样的结果,当时就在考虑是否有更好的替代品。有点崩溃啊。 还好,深深地求知欲和征服欲让我坚持下来了。
哈哈,这算不算Spring Security的一个Bug呢?没有任何的权限与资源的配置,就认为登录后的用户具有访问任何资源的权限,说起来有点可怕哈。

当然,当我将上述代码中被注释的4条配置放开后,Spring security奇迹般的恢复了活力。

接下来实现了jsp型URL的拦截之后,我又遇见了不能拦截action的情况,不过经过多次的配置和重启服务试验,终于发现,在配置Action与权限时,一定要在Action的路径前面加“/”斜杠,否则,Spring Security就会对该请求的URL熟视无睹,无视它的存在,即使你在Action的前后加上*号进行匹配也不会起任何作用,哈哈,不禁慨叹Spring Security的牛脾气。


第二种方法BTW

顺便提一下子,Spring Security3需要配置的过滤器是双重的,首先在web.xml中配置一个过滤器代理,参见上述web.xml中的springSecurityFilterChain配置。
我们通常设置过滤的url模式为/*,就是说任何的url访问都要进行过滤,工作量有点大哈。当然我们可以为之设置不同的过滤url模式,比如.action、.do、.jsp等。这样的话,遇到.action或.jsp或.do结尾的url访问,Spring Security就会突然站出来打截,若是其他的访问,Spring Security就会挥一挥手,潇洒地让你路过。
所以说,这个过滤器主要对大的方面进行拦截,一些细小的活儿,还是要交给第二重过滤器。 就是说,这第一重过滤器是个总代理,他威武地管理着一个过滤器链。

那么这第二重过滤器的配置,就是那些所谓的过滤器链,分别包括“记住我”、“登录”、“注销”、“url访问”等的过滤器,这个过滤器依顺序排开,形成一个过滤链条。具体拦截我们明细Url的是一个叫做FilterInterCeptor的伙计,我认为这个家伙是在整个过滤器链条中是最重要的一个,因为我们登录系统之后,要访问的任何资源都必须经得他的同意。 那么这第二重链条就设置在applicationContext-security.xml文件中的<http>元素下面。
什么,你看不到? 忘记告诉你了,从spring security2开始,就使用了命名空间,若你在<http>中设置了auto="true",Spring Security就会在服务启动时自动加载
所有的过滤器链,省事了吧!

第三种方法

当然,spring security3毕竟是西方国家的东西,以英文为主,使用习惯和文化的差异共存,况且为了适应大多数Web应用的权限管理,作者将Spring Security3打造的精简而灵活。精简指Spring Security3对用户和权限的表设计的非常简单,并且没有采用数据库来管理资源(URL)。这样的话,对于我们国人用户来说,是个很大的遗憾,这个遗憾甚至能够影响到我们对安全框架的选型。你想啊,在国内大多数项目中,均设置了比较复杂的权限控制,一般就会涉及到用户、角色、权限、资源4张表,若要加上4张表之间的对应关系表3张,得有7张表才行。

得7张表才行,但是Spring Security3才给我们提供了2张最简洁的表,这足以不能完成国人用户的项目应用。那么在对Spring Security3一无所知的情况下,
我们很容易就会放弃对该安全框架的选型。

还好,Spring Security3提供了灵活的扩展方法。具体应该扩展哪些类呢? 或者到底Spring Security3工作的流程如何,你不妨参看下面一篇文章,就会获得
一些启示,网址为:http://www.blogjava.net/youxia/archive/2008/12/07/244883.html , 哈哈,谢谢分享。

还有一个地址很有价值, http://wenku.baidu.com/view/4ec7e324ccbff121dd368364.html ,我就参考着上面的介绍扩展了4个类。

不过我得提一下,原文的作者为了考验你的耐性和自信心,故意在代码里面卖了几点小小的关子,因此若是完全按照作者的原文代码装配起来的权限系统,是不会那么顺利地工作的,天下似乎真是没有不花费力气的午餐!在装配完成后,我也是经过九九八十一难的折磨,在用户、角色、权限、资源的
“天下黄河九曲十八弯”里面盘旋迂回,终于到达了成功的彼岸。至此才对Spring Security有了更深层次的理解,更加佩服作者的良苦用心。 哈哈。

并扩展了User类以增加其相关的各类其他信息(如Email,职务,所在单位id等)。


相关的代码如下(包含5个关键类):

/*
*@(#)MyFilterSecurityInterceptor.java2011-3-23上午07:53:03
*
*Copyright2011bySparta
*/


packageavatar.base.security;

importjava.io.IOException;

importjavax.servlet.Filter;
importjavax.servlet.FilterChain;
importjavax.servlet.FilterConfig;
importjavax.servlet.ServletException;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;

importorg.springframework.security.access.SecurityMetadataSource;
importorg.springframework.security.access.intercept.AbstractSecurityInterceptor;
importorg.springframework.security.access.intercept.InterceptorStatusToken;
importorg.springframework.security.web.FilterInvocation;
importorg.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

/**
*该过滤器的主要作用就是通过spring著名的IoC生成securityMetadataSource。
*securityMetadataSource相当于本包中自定义的MyInvocationSecurityMetadataSourceService。
*该MyInvocationSecurityMetadataSourceService的作用提从数据库提取权限和资源,装配到HashMap中,
*供SpringSecurity使用,用于权限校验。
*
@authorsparta11/3/29
*
*/


publicclassMyFilterSecurityInterceptor
extendsAbstractSecurityInterceptor
implementsFilter{


privateFilterInvocationSecurityMetadataSourcesecurityMetadataSource;

publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)
throwsIOException,ServletException{

FilterInvocationfi
=newFilterInvocation(request,response,chain);
invoke(fi);

}


publicFilterInvocationSecurityMetadataSourcegetSecurityMetadataSource(){
returnthis.securityMetadataSource;
}


publicClass<?extendsObject>getSecureObjectClass(){
returnFilterInvocation.class;
}



publicvoidinvoke(FilterInvocationfi)throwsIOException,ServletException{

InterceptorStatusTokentoken
=super.beforeInvocation(fi);

try{
fi.getChain().doFilter(fi.getRequest(),fi.getResponse());
}
finally{
super.afterInvocation(token,null);
}


}



@Override
publicSecurityMetadataSourceobtainSecurityMetadataSource(){
returnthis.securityMetadataSource;
}



publicvoidsetSecurityMetadataSource(FilterInvocationSecurityMetadataSourcesecurityMetadataSource){
this.securityMetadataSource=securityMetadataSource;
}



publicvoiddestroy(){

}


publicvoidinit(FilterConfigfilterconfig)throwsServletException{

}



}




/*
*@(#)MyInvocationSecurityMetadataSourceService.java2011-3-23下午02:58:29
*
*Copyright2011bySparta
*/


packageavatar.base.security;

importjava.util.ArrayList;
importjava.util.Collection;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;

importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importorg.springframework.security.access.ConfigAttribute;
importorg.springframework.security.access.SecurityConfig;
importorg.springframework.security.core.GrantedAuthority;
importorg.springframework.security.core.context.SecurityContextHolder;
importorg.springframework.security.core.userdetails.UserDetails;
importorg.springframework.security.web.FilterInvocation;
importorg.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
importorg.springframework.security.web.util.AntUrlPathMatcher;
importorg.springframework.security.web.util.UrlMatcher;
importorg.springframework.stereotype.Service;

importavatar.base.security.dao.PubAuthoritiesResourcesHome;

/**
*最核心的地方,就是提供某个资源对应的权限定义,即getAttributes方法返回的结果。此类在初始化时,应该取到所有资源及其对应角色的定义。
*
*/

@Service
publicclassMyInvocationSecurityMetadataSourceServiceimplements
FilterInvocationSecurityMetadataSource
{

@Autowired
privatePubAuthoritiesResourcesHomepubAuthoritiesResourcesHome;

privateUrlMatcherurlMatcher=newAntUrlPathMatcher();

privatestaticMap<String,Collection<ConfigAttribute>>resourceMap=null;

publicMyInvocationSecurityMetadataSourceService(){
loadResourceDefine();
}


privatevoidloadResourceDefine(){
ApplicationContextcontext
=newClassPathXmlApplicationContext(
"classpath:applicationContext.xml");

SessionFactorysessionFactory
=(SessionFactory)context
.getBean(
"sessionFactory");

Sessionsession
=sessionFactory.openSession();

Stringusername
="";
Stringsql
="";

//在Web服务器启动时,提取系统中的所有权限。
sql="selectauthority_namefrompub_authorities";

List
<String>query=session.createSQLQuery(sql).list();

/*
*应当是资源为key,权限为value。资源通常为url,权限就是那些以ROLE_为前缀的角色。一个资源可以由多个权限来访问。
*sparta
*/

resourceMap
=newHashMap<String,Collection<ConfigAttribute>>();

for(Stringauth:query){
ConfigAttributeca
=newSecurityConfig(auth);

List
<String>query1=session
.createSQLQuery(
"selectb.resource_string"
+"fromPub_Authorities_Resourcesa,Pub_Resourcesb,"
+"Pub_authoritiescwherea.resource_id=b.resource_id"
+"anda.authority_id=c.authority_idandc.Authority_name='"
+auth+"'").list();

for(Stringres:query1){
Stringurl
=res;

/*
*判断资源文件和权限的对应关系,如果已经存在相关的资源url,则要通过该url为key提取出权限集合,将权限增加到权限集合中。
*sparta
*/

if(resourceMap.containsKey(url)){

Collection
<ConfigAttribute>value=resourceMap.get(url);
value.add(ca);
resourceMap.put(url,value);
}
else{
Collection
<ConfigAttribute>atts=newArrayList<ConfigAttribute>();
atts.add(ca);
resourceMap.put(url,atts);
}


}


}


}


@Override
publicCollection<ConfigAttribute>getAllConfigAttributes(){

returnnull;
}


//根据URL,找到相关的权限配置。
@Override
publicCollection<ConfigAttribute>getAttributes(Objectobject)
throwsIllegalArgumentException{

//object是一个URL,被用户请求的url。
Stringurl=((FilterInvocation)object).getRequestUrl();

intfirstQuestionMarkIndex=url.indexOf("?");

if(firstQuestionMarkIndex!=-1){
url
=url.substring(0,firstQuestionMarkIndex);
}


Iterator
<String>ite=resourceMap.keySet().iterator();

while(ite.hasNext()){
StringresURL
=ite.next();

if(urlMatcher.pathMatchesUrl(url,resURL)){

returnresourceMap.get(resURL);
}

}


returnnull;
}


@Override
publicbooleansupports(Class<?>arg0){

returntrue;
}


}



/*
*@(#)MyUserDetailsService.java2011-3-23上午09:04:31
*
*Copyright2011bySparta
*/


packageavatar.base.security;


importjava.util.ArrayList;
importjava.util.Collection;


importjavax.sql.DataSource;


importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.dao.DataAccessException;
importorg.springframework.security.core.GrantedAuthority;
importorg.springframework.security.core.userdetails.User;
importorg.springframework.security.core.userdetails.UserCache;
importorg.springframework.security.core.userdetails.UserDetails;
importorg.springframework.security.core.userdetails.UserDetailsService;
importorg.springframework.security.core.userdetails.UsernameNotFoundException;
importorg.springframework.stereotype.Service;

importavatar.base.security.dao.PubAuthoritiesResourcesHome;
importavatar.base.security.dao.PubUsersHome;


/**
*该类的主要作用是为SpringSecurity提供一个经过用户认证后的UserDetails。
*该UserDetails包括用户名、密码、是否可用、是否过期等信息。
*sparta11/3/29
*/

@Service
publicclassMyUserDetailsServiceimplementsUserDetailsService{

@Autowired
privatePubUsersHomepubUsersHome;

@Autowired
privatePubAuthoritiesResourcesHomepubAuthoritiesResourcesHome;

@Autowired
privateDataSourcedataSource;

@Autowired
privateUserCacheuserCache;

@Override
publicUserDetailsloadUserByUsername(Stringusername)
throwsUsernameNotFoundException,DataAccessException{

Collection
<GrantedAuthority>auths=newArrayList<GrantedAuthority>();


//得到用户的权限
auths=pubUsersHome.loadUserAuthoritiesByName(username);

Stringpassword
=null;

//取得用户的密码
password=pubUsersHome.getPasswordByUsername(username);

returnnewUser(username,password,true,"",true,true,true,auths);
}


//setPubUsersHome
publicvoidsetPubUsersHome(PubUsersHomepubUsersHome){
this.pubUsersHome=pubUsersHome;

}


publicPubUsersHomegetPubUsersHome(){
returnpubUsersHome;
}



//setPubAuthoritiesResourcesHome
publicvoidsetPubAuthoritiesResourcesHome(PubAuthoritiesResourcesHomepubAuthoritiesResourcesHome){
this.pubAuthoritiesResourcesHome=pubAuthoritiesResourcesHome;

}


publicPubAuthoritiesResourcesHomegetPubAuthoritiesResourcesHome(){
returnpubAuthoritiesResourcesHome;

}


//setDataSource
publicvoidsetDataSource(DataSourcedataSource){
this.dataSource=dataSource;
}


publicDataSourcegetDataSource(){
returndataSource;
}


//设置用户缓存功能。
publicvoidsetUserCache(UserCacheuserCache){
this.userCache=userCache;
}


publicUserCachegetUserCache(){
returnthis.userCache;
}


}


/*
*@(#)MyAccessDecisionManager.java2011-3-23下午04:41:12
*
*Copyright2011bySparta
*/


packageavatar.base.security;

importjava.util.Collection;
importjava.util.Iterator;

importorg.springframework.security.access.AccessDecisionManager;
importorg.springframework.security.access.AccessDeniedException;
importorg.springframework.security.access.ConfigAttribute;
importorg.springframework.security.access.SecurityConfig;
importorg.springframework.security.authentication.InsufficientAuthenticationException;
importorg.springframework.security.core.Authentication;
importorg.springframework.security.core.GrantedAuthority;

/**
*AccessdecisionManager在Springsecurity中是很重要的。
*
*在验证部分简略提过了,所有的Authentication实现需要保存在一个GrantedAuthority对象数组中。
*这就是赋予给主体的权限。GrantedAuthority对象通过AuthenticationManager
*保存到Authentication对象里,然后从AccessDecisionManager读出来,进行授权判断。
*
*SpringSecurity提供了一些拦截器,来控制对安全对象的访问权限,例如方法调用或web请求。
*一个是否允许执行调用的预调用决定,是由AccessDecisionManager实现的。
*这个AccessDecisionManager被AbstractSecurityInterceptor调用,
*它用来作最终访问控制的决定。这个AccessDecisionManager接口包含三个方法:
*
voiddecide(Authenticationauthentication,ObjectsecureObject,
List<ConfigAttributeDefinition>config)throwsAccessDeniedException;
booleansupports(ConfigAttributeattribute);
booleansupports(Classclazz);

从第一个方法可以看出来,AccessDecisionManager使用方法参数传递所有信息,这好像在认证评估时进行决定。
特别是,在真实的安全方法期望调用的时候,传递安全Object启用那些参数。
比如,让我们假设安全对象是一个MethodInvocation。
很容易为任何Customer参数查询MethodInvocation,
然后在AccessDecisionManager里实现一些有序的安全逻辑,来确认主体是否允许在那个客户上操作。
如果访问被拒绝,实现将抛出一个AccessDeniedException异常。

这个supports(ConfigAttribute)方法在启动的时候被
AbstractSecurityInterceptor调用,来决定AccessDecisionManager
是否可以执行传递ConfigAttribute。
supports(Class)方法被安全拦截器实现调用,
包含安全拦截器将显示的AccessDecisionManager支持安全对象的类型。
*/

publicclassMyAccessDecisionManagerimplementsAccessDecisionManager{

publicvoiddecide(Authenticationauthentication,Objectobject,
Collection
<ConfigAttribute>configAttributes)
throwsAccessDeniedException,InsufficientAuthenticationException{

if(configAttributes==null){
return;
}


Iterator
<ConfigAttribute>ite=configAttributes.iterator();

while(ite.hasNext()){

ConfigAttributeca
=ite.next();
StringneedRole
=((SecurityConfig)ca).getAttribute();

//ga为用户所被赋予的权限。needRole为访问相应的资源应该具有的权限。
for(GrantedAuthorityga:authentication.getAuthorities()){

if(needRole.trim().equals(ga.getAuthority().trim())){

return;
}


}


}


thrownewAccessDeniedException("");

}


publicbooleansupports(ConfigAttributeattribute){

returntrue;

}


publicbooleansupports(Class<?>clazz){
returntrue;

}



}


数据库的SQL及预置数据:

promptPL/SQLDeveloperimportfile
promptCreated
on2011年6月1日byAdministrator
setfeedbackoff
setdefineoff
promptCreatingSYS_AUTHORITIES
createtableSYS_AUTHORITIES
(
AUTHORITY_ID
VARCHAR2(32)notnull,
AUTHORITY_NAME
VARCHAR2(40),
AUTHORITY_DESC
VARCHAR2(100),
ENABLED
NUMBER(1),
ISSYS
NUMBER(1),
MODULE
VARCHAR2(4)
)
tablespaceSCJD
pctfree
10
initrans
1
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
comment
ontableSYS_AUTHORITIES
is'权限表';
comment
oncolumnSYS_AUTHORITIES.MODULE
is'所属的子系统,比如平台里面包括10个系统,分别为成本、作业、集输等。';
altertableSYS_AUTHORITIES
addconstraintPK_PUB_AUTHORITIESprimarykey(AUTHORITY_ID)
using
index
tablespaceSCJD
pctfree
10
initrans
2
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);

promptCreatingSYS_RESOURCES
createtableSYS_RESOURCES
(
RESOURCE_ID
VARCHAR2(32)notnull,
RESOURCE_NAME
VARCHAR2(100),
RESOURCE_DESC
VARCHAR2(100),
RESOURCE_TYPE
VARCHAR2(40),
RESOURCE_STRING
VARCHAR2(200),
PRIORITY
NUMBER(1),
ENABLED
NUMBER(1),
ISSYS
NUMBER(1),
MODULE
VARCHAR2(4)
)
tablespaceSCJD
pctfree
10
initrans
1
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
comment
ontableSYS_RESOURCES
is'资源表';
comment
oncolumnSYS_RESOURCES.PRIORITY
is'(暂不用,保留)';
comment
oncolumnSYS_RESOURCES.MODULE
is'所属的子系统,比如平台里面包括10个系统,分别为成本、作业、集输等。(暂不用,保留)';
altertableSYS_RESOURCES
addconstraintPK_PUB_RESOURCESprimarykey(RESOURCE_ID)
using
index
tablespaceSCJD
pctfree
10
initrans
2
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);

promptCreatingSYS_AUTHORITIES_RESOURCES
createtableSYS_AUTHORITIES_RESOURCES
(
ID
NUMBER(13)notnull,
AUTHORITY_ID
VARCHAR2(32),
RESOURCE_ID
VARCHAR2(32),
ENABLED
NUMBER(1)
)
tablespaceSCJD
pctfree
10
initrans
1
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
comment
ontableSYS_AUTHORITIES_RESOURCES
is'权限资源表';
altertableSYS_AUTHORITIES_RESOURCES
addconstraintPK_PUB_AUTHORITIES_REprimarykey(ID)
using
index
tablespaceSCJD
pctfree
10
initrans
2
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
altertableSYS_AUTHORITIES_RESOURCES
addconstraintFK_PUB_AUTHORITIES_RE_AUforeignkey(AUTHORITY_ID)
referencesSYS_AUTHORITIES(AUTHORITY_ID);
altertableSYS_AUTHORITIES_RESOURCES
addconstraintFK_PUB_AUTHORITIES_RE_REforeignkey(RESOURCE_ID)
referencesSYS_RESOURCES(RESOURCE_ID);

promptCreatingSYS_ROLES
createtableSYS_ROLES
(
ROLE_ID
VARCHAR2(32)notnull,
ROLE_NAME
VARCHAR2(40),
ROLE_DESC
VARCHAR2(100),
ENABLED
NUMBER(1),
ISSYS
NUMBER(1),
MODULE
VARCHAR2(4)
)
tablespaceSCJD
pctfree
10
initrans
1
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
comment
ontableSYS_ROLES
is'角色表';
comment
oncolumnSYS_ROLES.MODULE
is'所属的子系统,比如平台里面包括10个系统,分别为成本、作业、集输等。';
altertableSYS_ROLES
addconstraintPK_PUB_ROLESprimarykey(ROLE_ID)
using
index
tablespaceSCJD
pctfree
10
initrans
2
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);

promptCreatingSYS_ROLES_AUTHORITIES
createtableSYS_ROLES_AUTHORITIES
(
ID
NUMBER(13)notnull,
ROLE_ID
VARCHAR2(32),
AUTHORITY_ID
VARCHAR2(32),
ENABLED
NUMBER(1)
)
tablespaceSCJD
pctfree
10
initrans
1
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
comment
ontableSYS_ROLES_AUTHORITIES
is'角色权限表';
altertableSYS_ROLES_AUTHORITIES
addconstraintPK_PUB_ROLES_AUTHORITYprimarykey(ID)
using
index
tablespaceSCJD
pctfree
10
initrans
2
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
altertableSYS_ROLES_AUTHORITIES
addconstraintFK_PUB_ROLES_AUTHORITIES_AUforeignkey(AUTHORITY_ID)
referencesSYS_AUTHORITIES(AUTHORITY_ID);
altertableSYS_ROLES_AUTHORITIES
addconstraintFK_PUB_ROLES_AUTHORITIES_ROLESforeignkey(ROLE_ID)
referencesSYS_ROLES(ROLE_ID);

promptCreatingSYS_USERS
createtableSYS_USERS
(
USER_IDVARCHAR2(32)notnull,
USER_ACCOUNT
VARCHAR2(30),
USER_NAMEVARCHAR2(40),
USER_PASSWORD
VARCHAR2(100),
USER_DESC
VARCHAR2(100),
ENABLED
NUMBER(1),
ISSYS
NUMBER(1),
USER_DEPT
VARCHAR2(20),
USER_DUTY
VARCHAR2(10),
SUB_SYSTEM
VARCHAR2(30)
)
tablespaceSCJD
pctfree
10
initrans
1
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
comment
ontableSYS_USERS
is'用户表';
comment
oncolumnSYS_USERS.USER_PASSWORD
is'该密码是经加盐值加密的,格式为password{username}。比如用户的密码为user,用户名为user,那么通过MD5进行加密的串为:user{user}';
comment
oncolumnSYS_USERS.ISSYS
is'是否是超级用户';
comment
oncolumnSYS_USERS.USER_DEPT
is'所在单位';
comment
oncolumnSYS_USERS.USER_DUTY
is'经理或主任';
comment
oncolumnSYS_USERS.SUB_SYSTEM
is'该用户所负责的各子系统,可多个,中间用逗号分隔。(目前暂未用,作为保留字段)';
altertableSYS_USERS
addconstraintPK_PUB_USERSprimarykey(USER_ID)
using
index
tablespaceSCJD
pctfree
10
initrans
2
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);

promptCreatingSYS_USERS_ROLES
createtableSYS_USERS_ROLES
(
ID
NUMBER(13)notnull,
USER_IDVARCHAR2(32),
ROLE_ID
VARCHAR2(32),
ENABLED
NUMBER(1)
)
tablespaceSCJD
pctfree
10
initrans
1
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
comment
ontableSYS_USERS_ROLES
is'用户角色表';
altertableSYS_USERS_ROLES
addconstraintPK_PUB_USERS_ROLESprimarykey(ID)
using
index
tablespaceSCJD
pctfree
10
initrans
2
maxtrans
255
storage
(
initial64K
minextents
1
maxextentsunlimited
);
altertableSYS_USERS_ROLES
addconstraintFK_USERS_ROLES_ROLESforeignkey(ROLE_ID)
referencesSYS_ROLES(ROLE_ID);
altertableSYS_USERS_ROLES
addconstraintFK_USERS_ROLES_USERSforeignkey(USER_ID)
referencesSYS_USERS(USER_ID);

promptDisablingtriggers
forSYS_AUTHORITIES
altertableSYS_AUTHORITIESdisablealltriggers;
promptDisablingtriggers
forSYS_RESOURCES
altertableSYS_RESOURCESdisablealltriggers;
promptDisablingtriggers
forSYS_AUTHORITIES_RESOURCES
altertableSYS_AUTHORITIES_RESOURCESdisablealltriggers;
promptDisablingtriggers
forSYS_ROLES
altertableSYS_ROLESdisablealltriggers;
promptDisablingtriggers
forSYS_ROLES_AUTHORITIES
altertableSYS_ROLES_AUTHORITIESdisablealltriggers;
promptDisablingtriggers
forSYS_USERS
altertableSYS_USERSdisablealltriggers;
promptDisablingtriggers
forSYS_USERS_ROLES
altertableSYS_USERS_ROLESdisablealltriggers;
promptDisabling
foreignkeyconstraintsforSYS_AUTHORITIES_RESOURCES
altertableSYS_AUTHORITIES_RESOURCESdisableconstraintFK_PUB_AUTHORITIES_RE_AU;
altertableSYS_AUTHORITIES_RESOURCESdisableconstraintFK_PUB_AUTHORITIES_RE_RE;
promptDisabling
foreignkeyconstraintsforSYS_ROLES_AUTHORITIES
altertableSYS_ROLES_AUTHORITIESdisableconstraintFK_PUB_ROLES_AUTHORITIES_AU;
altertableSYS_ROLES_AUTHORITIESdisableconstraintFK_PUB_ROLES_AUTHORITIES_ROLES;
promptDisabling
foreignkeyconstraintsforSYS_USERS_ROLES
altertableSYS_USERS_ROLESdisableconstraintFK_USERS_ROLES_ROLES;
altertableSYS_USERS_ROLESdisableconstraintFK_USERS_ROLES_USERS;
promptDeletingSYS_USERS_ROLES
deletefromSYS_USERS_ROLES;
commit;
promptDeletingSYS_USERS
deletefromSYS_USERS;
commit;
promptDeletingSYS_ROLES_AUTHORITIES
deletefromSYS_ROLES_AUTHORITIES;
commit;
promptDeletingSYS_ROLES
deletefromSYS_ROLES;
commit;
promptDeletingSYS_AUTHORITIES_RESOURCES
deletefromSYS_AUTHORITIES_RESOURCES;
commit;
promptDeletingSYS_RESOURCES
deletefromSYS_RESOURCES;
commit;
promptDeletingSYS_AUTHORITIES
deletefromSYS_AUTHORITIES;
commit;
promptLoadingSYS_AUTHORITIES
insertintoSYS_AUTHORITIES(AUTHORITY_ID,AUTHORITY_NAME,AUTHORITY_DESC,ENABLED,ISSYS,MODULE)
values('1303910437484','AUTH_xxx','xxx',null,null,'01');
insertintoSYS_AUTHORITIES(AUTHORITY_ID,AUTHORITY_NAME,AUTHORITY_DESC,ENABLED,ISSYS,MODULE)
values('AUTH_LOGIN4','AUTH_LOGIN','登录',1,0,'01');
insertintoSYS_AUTHORITIES(AUTHORITY_ID,AUTHORITY_NAME,AUTHORITY_DESC,ENABLED,ISSYS,MODULE)
values('AUTH_AFTERLOGINWELCOME5','AUTH_AFTERLOGINWELCOME','登录后欢迎界面',1,0,'01');
insertintoSYS_AUTHORITIES(AUTHORITY_ID,AUTHORITY_NAME,AUTHORITY_DESC,ENABLED,ISSYS,MODULE)
values('AUTH_XTSZ_DEPT1','AUTH_XTSZ_DEPT','单位设置',1,0,'01');
insertintoSYS_AUTHORITIES(AUTHORITY_ID,AUTHORITY_NAME,AUTHORITY_DESC,ENABLED,ISSYS,MODULE)
values('AUTH_XTSZ_USER2','AUTH_XTSZ_USER','用户设置、横向查询',1,0,'01');
insertintoSYS_AUTHORITIES(AUTHORITY_ID,AUTHORITY_NAME,AUTHORITY_DESC,ENABLED,ISSYS,MODULE)
values('AUTH_NODE_MGR3','AUTH_NODE_MGR','节点管理、纵向查询',1,0,'01');
commit;
prompt
6recordsloaded
promptLoadingSYS_RESOURCES
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('1303909883031','ff','ff','action','b.jsp',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('1303909847687','ff1','ff1','action','b.jsp',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('node_mgr3','node_mgr','节点管理','url','/*/*/Tree.jsp',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('login4','login','登录','url','/login.jsp',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('index5','index','登录后欢迎页面','url','/index.jsp',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('resources_mgr','resources_mgr','资源管理','action','/managerResource',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('horizontal_qry6','horizontal_qry','横向查询','action','/horizontalQuery',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('vertical_qry7','vertical_qry','纵向查询','action','/verticalQuery',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('dep_mgr1','dep_mgr','单位管理','action','/UnitsManager',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('user_mgr2','user_mgr','用户管理','action','/managerUser',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('authority_mgr','authority_mgr','权限管理','action','/managerAuthority',null,1,0,null);
insertintoSYS_RESOURCES(RESOURCE_ID,RESOURCE_NAME,RESOURCE_DESC,RESOURCE_TYPE,RESOURCE_STRING,PRIORITY,ENABLED,ISSYS,MODULE)
values('role_mgr','role_mgr','角色管理','action','/managerRole',null,null,null,null);
commit;
prompt
12recordsloaded
promptLoadingSYS_AUTHORITIES_RESOURCES
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(1,'AUTH_AFTERLOGINWELCOME5','index5',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(2,'AUTH_LOGIN4','login4',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(3,'AUTH_NODE_MGR3','node_mgr3',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(4,'AUTH_XTSZ_DEPT1','dep_mgr1',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(5,'AUTH_XTSZ_USER2','user_mgr2',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(7,'AUTH_XTSZ_USER2','horizontal_qry6',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(8,'AUTH_XTSZ_DEPT1','vertical_qry7',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(12,'AUTH_XTSZ_USER2','role_mgr',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(10,'AUTH_XTSZ_USER2','resources_mgr',1);
insertintoSYS_AUTHORITIES_RESOURCES(ID,AUTHORITY_ID,RESOURCE_ID,ENABLED)
values(11,'AUTH_XTSZ_USER2','authority_mgr',1);
commit;
prompt
10recordsloaded
promptLoadingSYS_ROLES
insertintoSYS_ROLES(ROLE_ID,ROLE_NAME,ROLE_DESC,ENABLED,ISSYS,MODULE)
values('1303463518765','ROLE_dd1','dd1',1,0,'01');
insertintoSYS_ROLES(ROLE_ID,ROLE_NAME,ROLE_DESC,ENABLED,ISSYS,MODULE)
values('1303463949640','ROLE_rr1','rr1',1,0,'02');
insertintoSYS_ROLES(ROLE_ID,ROLE_NAME,ROLE_DESC,ENABLED,ISSYS,MODULE)
values('ROLE_PLATFORMADMIN1','ROLE_PLATFORMADMIN','可管理整个平台的用户、单位设置。',1,1,'01');
insertintoSYS_ROLES(ROLE_ID,ROLE_NAME,ROLE_DESC,ENABLED,ISSYS,MODULE)
values('ROLE_USER2','ROLE_USER','普通用户',1,0,'01');
insertintoSYS_ROLES(ROLE_ID,ROLE_NAME,ROLE_DESC,ENABLED,ISSYS,MODULE)
values('ROLE_LOGINTOWELCOME4','ROLE_LOGINTOWELCOME','仅登录到欢迎界面!',1,0,'01');
insertintoSYS_ROLES(ROLE_ID,ROLE_NAME,ROLE_DESC,ENABLED,ISSYS,MODULE)
values('ROLE_SYSADMIN3','ROLE_SYSADMIN','可管理本系统的用户、单位设置。',1,0,'01');
insertintoSYS_ROLES(ROLE_ID,ROLE_NAME,ROLE_DESC,ENABLED,ISSYS,MODULE)
values('ROLE_WORK','ROLE_WORK','作业子系统的角色(试验)',1,0,'02');
insertintoSYS_ROLES(ROLE_ID,ROLE_NAME,ROLE_DESC,ENABLED,ISSYS,MODULE)
values('ROLE_LOGIN','ROLE_LOGIN','系统登录',1,0,'01');
commit;
prompt
8recordsloaded
promptLoadingSYS_ROLES_AUTHORITIES
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(1,'ROLE_LOGINTOWELCOME4','AUTH_AFTERLOGINWELCOME5',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(2,'ROLE_PLATFORMADMIN1','AUTH_AFTERLOGINWELCOME5',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(3,'ROLE_PLATFORMADMIN1','AUTH_LOGIN4',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(4,'ROLE_PLATFORMADMIN1','AUTH_NODE_MGR3',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(5,'ROLE_PLATFORMADMIN1','AUTH_XTSZ_DEPT1',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(6,'ROLE_PLATFORMADMIN1','AUTH_XTSZ_USER2',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(7,'ROLE_SYSADMIN3','AUTH_XTSZ_DEPT1',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(8,'ROLE_SYSADMIN3','AUTH_XTSZ_USER2',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(9,'ROLE_USER2','AUTH_LOGIN4',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(10,'ROLE_LOGINTOWELCOME4','AUTH_LOGIN4',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(11,'ROLE_USER2','AUTH_AFTERLOGINWELCOME5',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(1303463962718,'1303463949640','AUTH_LOGIN4',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(1303463972234,'ROLE_WORK','AUTH_LOGIN4',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(1303463972235,'ROLE_WORK','AUTH_AFTERLOGINWELCOME5',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(1303463972250,'ROLE_WORK','AUTH_XTSZ_DEPT1',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(1303463972251,'ROLE_WORK','AUTH_XTSZ_USER2',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(1303463972265,'ROLE_WORK','AUTH_NODE_MGR3',1);
insertintoSYS_ROLES_AUTHORITIES(ID,ROLE_ID,AUTHORITY_ID,ENABLED)
values(1303287600015,'ROLE_LOGIN','AUTH_LOGIN4',1);
commit;
prompt
18recordsloaded
promptLoadingSYS_USERS
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('1304494573750','lxb','lxb','c7d3f4c857bc8c145d6e5d40c1bf23d9',null,1,0,'10011001',null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('1304490737406','lxb','lxb','c7d3f4c857bc8c145d6e5d40c1bf23d9',null,1,0,'10011001',null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('1304574079546','ddd','ddd','0a4f6a961276619f7f91356bcba5a746',null,0,0,null,null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('1304573363921','lxb','卢小兵','09eb37d219cfa835db40e5ab587f7082','普通仅登录到欢迎界面!',0,0,'1001',null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('1304573484515','lll','lll','47acedc22cef8c3762c21a435e262d67',null,1,0,'1001',null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('admin1','admin','系统管理员','ceb4f32325eda6142bd65215f4c0f371','超级系统管理员',1,1,'1001',null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('user2','user','普通用户','47a733d60998c719cf3526ae7d106d13','普通用户',1,0,'1001',null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('sysUser3','sysUser','系统设置维护','8f0295328c34f8eedc2362e9f4a10b7e','系统设置用户',1,0,'1001',null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('lxb4','lxb','卢小兵','c7d3f4c857bc8c145d6e5d40c1bf23d9','普通仅登录到欢迎界面!',1,0,'1001',null,'01');
insertintoSYS_USERS(USER_ID,USER_ACCOUNT,USER_NAME,USER_PASSWORD,USER_DESC,ENABLED,ISSYS,USER_DEPT,USER_DUTY,SUB_SYSTEM)
values('1304566319625','lxb5','lx5','1abe40ed6d0da1c834586e8ecef61fe7',null,0,0,'10011001',null,'01');
commit;
prompt
10recordsloaded
promptLoadingSYS_USERS_ROLES
insertintoSYS_USERS_ROLES(ID,USER_ID,ROLE_ID,ENABLED)
values(1,'admin1','ROLE_PLATFORMADMIN1',1);
insertintoSYS_USERS_ROLES(ID,USER_ID,ROLE_ID,ENABLED)
values(2,'sysUser3','ROLE_SYSADMIN3',1);
insertintoSYS_USERS_ROLES(ID,USER_ID,ROLE_ID,ENABLED)
values(3,'user2','ROLE_USER2',1);
insertintoSYS_USERS_ROLES(ID,USER_ID,ROLE_ID,ENABLED)
values(4,'lxb4','ROLE_LOGINTOWELCOME4',1);
insertintoSYS_USERS_ROLES(ID,USER_ID,ROLE_ID,ENABLED)
values(5,'1304573484515','1303463518765',null);
commit;
prompt
5recordsloaded
promptEnabling
foreignkeyconstraintsforSYS_AUTHORITIES_RESOURCES
altertableSYS_AUTHORITIES_RESOURCESenableconstraintFK_PUB_AUTHORITIES_RE_AU;
altertableSYS_AUTHORITIES_RESOURCESenableconstraintFK_PUB_AUTHORITIES_RE_RE;
promptEnabling
foreignkeyconstraintsforSYS_ROLES_AUTHORITIES
altertableSYS_ROLES_AUTHORITIESenableconstraintFK_PUB_ROLES_AUTHORITIES_AU;
altertableSYS_ROLES_AUTHORITIESenableconstraintFK_PUB_ROLES_AUTHORITIES_ROLES;
promptEnabling
foreignkeyconstraintsforSYS_USERS_ROLES
altertableSYS_USERS_ROLESenableconstraintFK_USERS_ROLES_ROLES;
altertableSYS_USERS_ROLESenableconstraintFK_USERS_ROLES_USERS;
promptEnablingtriggers
forSYS_AUTHORITIES
altertableSYS_AUTHORITIESenablealltriggers;
promptEnablingtriggers
forSYS_RESOURCES
altertableSYS_RESOURCESenablealltriggers;
promptEnablingtriggers
forSYS_AUTHORITIES_RESOURCES
altertableSYS_AUTHORITIES_RESOURCESenablealltriggers;
promptEnablingtriggers
forSYS_ROLES
altertableSYS_ROLESenablealltriggers;
promptEnablingtriggers
forSYS_ROLES_AUTHORITIES
altertableSYS_ROLES_AUTHORITIESenablealltriggers;
promptEnablingtriggers
forSYS_USERS
altertableSYS_USERSenablealltriggers;
promptEnablingtriggers
forSYS_USERS_ROLES
altertableSYS_USERS_ROLESenablealltriggers;
setfeedbackon
setdefineon
promptDone.


相关配置文件:

web.xml与第一种方法同。

applicationContext-security.xml:

<?xmlversion="1.0"encoding="UTF-8"?>

<b:beansxmlns="http://www.springframework.org/schema/security"
xmlns:b
="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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd"
>


<httpauto-config="true"access-denied-page="/accessDenied.jsp">
<!--不要过滤图片等静态资源-->
<intercept-urlpattern="/**/*.jpg"filters="none"/>
<intercept-urlpattern="/**/*.png"filters="none"/>
<intercept-urlpattern="/**/*.gif"filters="none"/>
<intercept-urlpattern="/**/*.css"filters="none"/>
<intercept-urlpattern="/**/*.js"filters="none"/>
<!--登录页面和忘记密码页面不过滤-->
<intercept-urlpattern="/login.jsp"filters="none"/>
<intercept-urlpattern="/jsp/forgotpassword.jsp"
filters
="none"/>

<form-loginlogin-page="/login.jsp"
authentication-failure-url
="/login.jsp?error=true"
default-target-url
="/index.jsp"/>

<!--"记住我"功能,采用持久化策略(将用户的登录信息存放在数据库表中)-->
<remember-medata-source-ref="dataSource"/>

<!--检测失效的sessionId,超时时定位到另外一个URL-->
<session-managementinvalid-session-url="/sessionTimeout.jsp"/>


<!--增加一个自定义的filter,放在FILTER_SECURITY_INTERCEPTOR之前,
实现用户、角色、权限、资源的数据库管理。
-->
<custom-filterref="myFilter"before="FILTER_SECURITY_INTERCEPTOR"/>


</http>


<!--一个自定义的filter,必须包含authenticationManager,
accessDecisionManager,securityMetadataSource三个属性。
-->
<b:beanid="myFilter"
class
="avatar.base.security.MyFilterSecurityInterceptor">
<b:propertyname="authenticationManager"
ref
="authenticationManager"/>
<b:propertyname="accessDecisionManager"
ref
="myAccessDecisionManager"/>
<b:propertyname="securityMetadataSource"
ref
="mySecurityMetadataSource"/>
</b:bean>



<!--注意能够为authentication-manager设置alias别名-->
<authentication-manageralias="authenticationManager">
<authentication-provideruser-service-ref="userDetailsManager">
<password-encoderref="passwordEncoder">
<salt-sourceuser-property="username"/>
</password-encoder>
</authentication-provider>
</authentication-manager>


<!--访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源。-->
<b:beanid="myAccessDecisionManager"
class
="avatar.base.security.MyAccessDecisionManager">
</b:bean>


<!--资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色去访问。-->
<b:beanid="mySecurityMetadataSource"
class
="avatar.base.security.MyInvocationSecurityMetadataSourceService">
</b:bean>

</b:beans>


applicationContext-service.xml:

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util
="http://www.springframework.org/schema/util"
xmlns:jee
="http://www.springframework.org/schema/jee"
xmlns:aop
="http://www.springframework.org/schema/aop"
xmlns:tx
="http://www.springframework.org/schema/tx"
xmlns:context
="http://www.springframework.org/schema/context"
xsi:schemaLocation
="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd"
>


<!--定义上下文返回的消息的国际化。-->
<beanid="messageSource"
class
="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<propertyname="basename"
value
="classpath:org/springframework/security/messages_zh_CN"/>
</bean>

<!--
事件监听:实现了ApplicationListener监听接口,
包括AuthenticationCredentialsNotFoundEvent事件,
AuthorizationFailureEvent事件,AuthorizedEvent事件,PublicInvocationEvent事
件。
-->
<bean
class="org.springframework.security.authentication.event.LoggerListener"/>

<!--用户的密码加密或解密-->
<beanid="passwordEncoder"
class
="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>


<!--用户详细信息管理:数据源、用户缓存(通过数据库管理用户、角色、权限、资源)。-->
<beanid="userDetailsManager"class="avatar.base.security.MyUserDetailsService">
<propertyname="pubUsersHome"ref="pubUsersHome"/>
<propertyname="pubAuthoritiesResourcesHome"ref="pubAuthoritiesResourcesHome"/>
<propertyname="dataSource"ref="dataSource"/>
<propertyname="userCache"ref="userCache"/>
</bean>

<!--启用用户的缓存功能-->
<beanid="userCache"
class
="org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache">
<propertyname="cache"ref="userEhCache"/>
</bean>

<beanid="userEhCache"class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<propertyname="cacheName"value="userCache"/>
<propertyname="cacheManager"ref="cacheManager"/>
</bean>

<beanid="cacheManager"
class
="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>


<!--springsecurity自带的与权限有关的数据读写Jdbc模板-->
<beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">
<propertyname="dataSource"ref="dataSource"/>
</bean>

</beans>


第三种方法扩展后Spring Security3.0.2的验证和授权方法

为了叙述的严谨性,这里说的是Spring Security3.0.2,而非其他版本,这是因为我只读过Spring Security3.0.2的代码,并且在该版本上面扩展自定义的
动态管理用户、角色、权限和资源成功。 估计其他版本的验证和授权方法是差不太多的,因为没有接触过,也不敢大胆猜测。

在扩展后的Spring Security3.0.2中,验证及授权的过程如下:
1、当Web服务器启动时,通过Web.xml中对于Spring Security的配置,加载过滤器链,那么在加载MyFilterSecurityInterceptor类时,会注入MyInvocationSecurityMetadataSourceService、MyUserDetailsService、MyAccessDecisionManager类。

2、该MyInvocationSecurityMetadataSourceService类在执行时会提取数据库中所有的用户权限,形成权限列表;
并循环该权限列表,通过每个权限再从数据库中提取出该权限所对应的资源列表,并将资源(URL)作为key,权限列表作为value,形成Map结构的数据。

3、当用户登录时,AuthenticationManager进行响应,通过用户输入的用户名和密码,然后再根据用户定义的密码算法和盐值等进行计算并和数据库比对,
当正确时通过验证。此时MyUserDetailsService进行响应,根据用户名从数据库中提取该用户的权限列表,组合成UserDetails供Spring Security使用。

4、当用户点击某个功能时,触发MyAccessDecisionManager类,该类通过decide方法对用户的资源访问进行拦截。
用户点击某个功能时,实际上是请求某个URL或Action, 无论.jsp也好,.action或.do也好,在请求时无一例外的表现为URL。
还记得第2步时那个Map结构的数据吗? 若用户点击了"login.action"这个URL之后,那么这个URL就跟那个Map结构的数据中的key对比,若两者相同,
则根据该url提取出Map结构的数据中的value来,这说明:若要请求这个URL,必须具有跟这个URL相对应的权限值。这个权限有可能是一个单独的权限,
也有可能是一个权限列表,也就是说,一个URL有可能被多种权限访问。

那好,我们在MyAccessDecisionManager类的decide这个方法里,将通过URL取得的权限列表进行循环,然后跟第3步中登录的用户所具有的权限进行比对,若相同,则表明该用户具有访问该资源的权利。 不大明白吧? 简单地说, 在数据库中我们定义了访问“LOGIN”这个URL必须是具有ROLE_ADMIN权限的人来访问,那么,登录用户恰恰具有该ROLE_ADMIN权限,两者的比对过程中,就能够返回TRUE,可以允许该用户进行访问。就这么简单!

不过在第2步的时候,一定要注意,MyInvocationSecurityMetadataSoruceService类的loadResourceDefine()方法中,形成以URL为key,权限列表为value的Map时,
要注意key和Value的对应性,避免Value的不正确对应形成重复,这样会导致没有权限的人也能访问到不该访问到的资源。
还有getAttributes()方法,要有 url.indexOf("?")这样的判断,要通过判断对URL特别是Action问号之前的部分进行匹配,防止用户请求的带参数的URL与你数据库中定义的URL不匹配,造成访问拒绝!

第三种方法BTW

当然,你在设计了7张表之后,那么对于这些之间相互关联的关系内容及信息内容,就得由你来进行维护了,大约有用户、角色、权限、资源的增删改查,并还需要设置用户和角色、角色和权限、权限和资源之间的关系。可考虑分为三个菜单进行维护,用户设置、角色设置、资源设置。 在用户设置里分别管理用户、用户与角色的关系;在角色设置里管理角色、角色与权限的关系; 在资源设置里分别管理权限、权限与资源的关系等。


第四种方法

第四种方法就是直接修改源码以达到第三种方法的效果。

本来准备是直接从源码修改来的, 但是始终认为修改源码并非终极解决之道,有违OO的精神本质,再者由于时间关系,只是对代码进行了研究,但并没有进行实现或验证。只待以后时间稍稍宽松时再做为兴趣进行研究,在次不过多的讲解。但据我从代码上来看,一是将从配置文件中获取用户及权限的功能修改为从数据库中提取出来;二是将从配置文件中获取权限和资源的对应关系修改为从数据库中提取;三是修改User增加相关信息等。

始终还是围绕着JdbcDaoImpl和DefaultFilterInvocationSecurityMetadataSource还有User这3个类进行修改。
以实现从数据库提取用户、角色、权限和资源信息。

有兴趣的就先试试吧,等试好了告诉我一声哈。

Spring Security的优缺点

不可否认,Spring Security依赖于Spring的Ioc、AOP等机制,横切开系统的业务组件,将通用的权限功能注入到业务组件内部,实现了通用功能和业务功能的无缝整合,但又保证了通用功能和业务功能的实现上的分离,省却了一部分工作量,这是其存在的最重要意义。

但又不可否认,Spring Security所具有的缺乏动态资源管理的硬伤(若是能够提供用户、角色、权限和资源的数据库管理,并且提供管理界面那实在是太完美了,可惜这两样一样都不能实现),又令国人用户爱恨交加。

该何去何从,就请自己做个选择吧!
分享到:
评论
1 楼 y90055015 2012-06-27  
请问,如果需要结合cas sso,应该如何调整配置?org.springframework.security.cas.web.CasAuthenticationFilter也是需要配置成custom-filter

相关推荐

    spring security3 中文版本

    spring security3 中文版本

    Spring Security 3.pdf

    Spring Security 3.pdf Spring Security 3.pdf Spring Security 3.pdf Spring Security 3.pdf

    Spring Security 资料合集

    Spring Security三份资料,实战Spring Security 3.x.pdf;Spring Security 3.pdf;Spring Security使用手册.pdf

    spring security spring security

    spring security spring security 中文文档

    springSecurity3例子

    简单的 springSecurity3例子代码

    精彩:Spring Security 演讲PPT

    3、Spring Security 2.x Overview 4、Dive Into Spring Security Authentication Authorization 5、Development Experiences & Demo 6、Q & A 张明星 5年以上保险、电信大中型项目开发经验,对JavaEE有较深入理解...

    spring security3动态权限

    struts2 + spring3 + hibernate3 + spring security3 + mysql + tomcat sys_users;sys_roles;sys_authorities;sys_resources;sys_users_roles;sys_roles_authorities;sys_authorities_resources; PS:此项目运行不...

    Spring Security实战源码

    ssecurity-pageClass项目是Spring Security实战(五)的源码; ssecurity-customFilter项目是Spring Security实战(六)的源码; ssecurity-rememberMe项目是Spring Security实战(七)的源码; 本人开发工具是IDEA...

    Spring Security3 Demo

    Spring Security3 Demo ,根据Spring Security 安全权限管理手册 整理出的例子。 通过eclipse部署。

    Spring Security in Action

    Spring Security in Action

    spring security 3 登录 退出 认证 最少配置

    项目应用到spring3,security3,hibernate4,struts2;应用中涉及到安全认证,目前项目有独立的统一认证网关,所以登录时只需要将安全认证网关的认证后信息塞到spring security中,由security3来管理用户的权限设置。...

    Spring Security3

    Spring Security3

    spring spring security2.5 jar

    spring security2.5 jar 和spring security2.5 整合必须的jar包

    spring3+struts2+hibernate3+spring security3 权限管理

    (1)该项目是基于spring3+struts2+hibernate3+spring security3的权限管理项目 (2)后台我已经实现了权限管理,包括用户,角色和资源的分配。前台实现了spring security3的管理 (3)网上案例普遍是后台单一登陆。...

    springsecurity学习笔记

    三更springsecurity学习笔记

    spring security3 jar包

    spring security3 安全框架

    SpringSecurity.zip

    ​ Spring Security:spring家族一员。是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转...

    SpringSecurity项目

    springsecurity是一个功能强大且高度可定制的身份验证和访问控制框架。springsecurity是一个专注于为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring安全性的真正威力在于它可以很容易地扩展以...

    Spring Security 参考手册Spring Security中文版

    很多独立软件供应商,因为灵活的身份验证模式二选择Spring Security。这样做允许他们快速的集成到他们的终端客户需求的解决方案而不用进行大量工程或者改变客户的环境。如果上面的验证机制不符合你的需求,Spring ...

    SpringSecurity学习总结源代码

    SpringSecurity学习总结源代码

Global site tag (gtag.js) - Google Analytics