Spring Security 3.1.1安全控制的例子(一)

关于spring security的例子有很多,但随着其版本的更新,有些配置也在不断变化,本实例采用spring3.1.1、spring security3.1.1;我参考了很多例子不断摸索总算弄出来个完整的例子,当然不免拷贝之处,我觉得最重要的是理解并加以运用,大家共同学习吧。。。

实现方式:spring3 + hibernate4 + jsf2

部署环境:jdk1.6、eclipse 3.5.2、tomcat 6.0.21、mysql 5

以上都是解压缩版,具体请到官网查看下载。

一、数据库(springframe

这里还是常用的资源权限模型(以下数据表SQL直接在Navicat for MySQL中运行即可):

Nativcat中运行SQL脚本

用户表users

  
  
  
  
  1. -- ----------------------------  
  2. -- Table structure for `users`  
  3. -- ----------------------------  
  4. DROP TABLE IF EXISTS `users`;  
  5. CREATE TABLE `users` (  
  6.   `ID` int(11) NOT NULL,  
  7.   `ACCOUNT` varchar(50) DEFAULT NULL,  
  8.   `ENABLE` int(11) DEFAULT NULL,  
  9.   `PASSWORDvarchar(50) DEFAULT NULL,  
  10.   PRIMARY KEY (`ID`),  
  11.   UNIQUE KEY `ID` (`ID`)  
  12. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;  
  13.  
  14. -- ----------------------------  
  15. -- Records of users  
  16. -- ----------------------------  
  17. INSERT INTO `users` VALUES ('100''admin''1''ceb4f32325eda6142bd65215f4c0f371');  
  18. INSERT INTO `users` VALUES ('101''user''1''47a733d60998c719cf3526ae7d106d13');  
  19. INSERT INTO `users` VALUES ('102''u''1''deeb9de5f0ad8e12b8f7fe7e0e318d76');  
  20. INSERT INTO `users` VALUES ('103''u1''1''76366d239fe64a4d5b9d9c07446e7764'); 

角色表roles

  
  
  
  
  1. -- ----------------------------  
  2. -- Table structure for `roles`  
  3. -- ----------------------------  
  4. DROP TABLE IF EXISTS `roles`;  
  5. CREATE TABLE `roles` (  
  6.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  7.   `namevarchar(255) DEFAULT NULL,  
  8.   `enable` int(11) DEFAULT NULL,  
  9.   PRIMARY KEY (`id`)  
  10. ) ENGINE=MyISAM AUTO_INCREMENT=202 DEFAULT CHARSET=utf8;  
  11.  
  12. -- ----------------------------  
  13. -- Records of roles  
  14. -- ----------------------------  
  15. INSERT INTO `roles` VALUES ('200''ROLE_ADMIN''1');  
  16. INSERT INTO `roles` VALUES ('201''ROLE_USER''1'); 

资源表resources

  
  
  
  
  1. -- ----------------------------  
  2. -- Table structure for `resources`  
  3. -- ----------------------------  
  4. DROP TABLE IF EXISTS `resources`;  
  5. CREATE TABLE `resources` (  
  6.   `ID` varchar(255) NOT NULL,  
  7.   `MEMO` longtext,  
  8.   `NAMEvarchar(50) DEFAULT NULL,  
  9.   `PRIORITY` int(11) DEFAULT NULL,  
  10.   `TYPE` varchar(11) DEFAULT NULL,  
  11.   `URL` longtext,  
  12.   PRIMARY KEY (`ID`),  
  13.   UNIQUE KEY `ID` (`ID`)  
  14. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;  
  15.  
  16. -- ----------------------------  
  17. -- Records of resources  
  18. -- ----------------------------  
  19. INSERT INTO `resources` VALUES ('400'null'index''1''URL''/index.jsf');  
  20. INSERT INTO `resources` VALUES ('401'null'admin''1''URL''/admin.jsf');  
  21. INSERT INTO `resources` VALUES ('402'null'index1''1''URL''/index2.jsf'); 

用户角色中间表users_roles

  
  
  
  
  1. -- ----------------------------  
  2. -- Table structure for `users_roles`  
  3. -- ----------------------------  
  4. DROP TABLE IF EXISTS `users_roles`;  
  5. CREATE TABLE `users_roles` (  
  6.   `uid` int(11) NOT NULL,  
  7.   `rid` int(11) NOT NULL,  
  8.   PRIMARY KEY (`uid`,`rid`),  
  9.   KEY `FKF6CCD9C6CBF0213D` (`uid`),  
  10.   KEY `FKF6CCD9C6CBC416AF` (`rid`)  
  11. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;  
  12.  
  13. -- ----------------------------  
  14. -- Records of users_roles  
  15. -- ----------------------------  
  16. INSERT INTO `users_roles` VALUES ('100''200');  
  17. INSERT INTO `users_roles` VALUES ('100''201');  
  18. INSERT INTO `users_roles` VALUES ('101''201');  
  19. INSERT INTO `users_roles` VALUES ('102''201');  
  20. INSERT INTO `users_roles` VALUES ('103''201'); 

角色资源中间表roles_resources

  
  
  
  
  1. -- ----------------------------  
  2. -- Table structure for `roles_resources`  
  3. -- ----------------------------  
  4. DROP TABLE IF EXISTS `roles_resources`;  
  5. CREATE TABLE `roles_resources` (  
  6.   `rid` int(11) NOT NULL,  
  7.   `rsid` varchar(255) NOT NULL,  
  8.   PRIMARY KEY (`rsid`,`rid`),  
  9.   KEY `FKAF06BF23CBC416AF` (`rid`),  
  10.   KEY `FKAF06BF23B74E21A6` (`rsid`)  
  11. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;  
  12.  
  13. -- ----------------------------  
  14. -- Records of roles_resources  
  15. -- ----------------------------  
  16. INSERT INTO `roles_resources` VALUES ('200''400');  
  17. INSERT INTO `roles_resources` VALUES ('201''400');  
  18. INSERT INTO `roles_resources` VALUES ('200''401');  
  19. INSERT INTO `roles_resources` VALUES ('200''402');  
  20. INSERT INTO `roles_resources` VALUES ('201''402'); 

二、web工程

eclipse下New->Dynamic Web project,输入工程名jweb-spring->Finish

1. xml 配置文件:

web.xml 配置

  
  
  
  
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
  5.     id="WebApp_ID" version="2.5"> 
  6.      
  7.     <context-param> 
  8.         <description>JSF状态保存在客户端</description> 
  9.         <param-name>javax.faces.STATE_SAVING_METHOD</param-name> 
  10.         <param-value>client</param-value> 
  11.     </context-param> 
  12.     <!-- JSF2.0的模式配置,开发模式下会在调试时报更加详细的错误--> 
  13.     <context-param> 
  14.         <param-name>javax.faces.PROJECT_STAGE</param-name> 
  15.         <param-value>Development</param-value> 
  16.     </context-param> 
  17.     <context-param> 
  18.         <param-name>javax.faces.CONFIG_FILES</param-name> 
  19.         <param-value>/WEB-INF/faces-config.xml</param-value> 
  20.     </context-param> 
  21.     <!-- JSF2.0的配置--> 
  22.     <servlet> 
  23.         <servlet-name>Faces Servlet</servlet-name> 
  24.         <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> 
  25.         <load-on-startup>1</load-on-startup> 
  26.     </servlet> 
  27.     <servlet-mapping> 
  28.         <servlet-name>Faces Servlet</servlet-name> 
  29.         <url-pattern>*.jsf</url-pattern> 
  30.     </servlet-mapping> 
  31.     <servlet-mapping> 
  32.         <servlet-name>Faces Servlet</servlet-name> 
  33.         <url-pattern>*.faces</url-pattern> 
  34.     </servlet-mapping> 
  35.       
  36.     <!-- Spring ContextLocation --> 
  37.     <context-param> 
  38.         <param-name>contextConfigLocation</param-name> 
  39.         <param-value>/WEB-INF/applicationContext*.xml</param-value> 
  40.     </context-param> 
  41.     <!-- spring启动监听器 --> 
  42.     <listener> 
  43.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  44.     </listener> 
  45.     <listener> 
  46.         <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 
  47.     </listener> 
  48.       
  49.     <welcome-file-list> 
  50.         <welcome-file>/index.xhtml</welcome-file> 
  51.     </welcome-file-list> 
  52.       
  53.     <!-- 解决Hibernate的延迟加载造成的Session提前关闭问题,设置该项使Session保持Request请求完成才关闭Session --> 
  54.     <filter> 
  55.         <filter-name>openSessionInViewFilter</filter-name> 
  56.         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> 
  57.         <init-param>    
  58.             <param-name>sessionFactoryBeanName</param-name>    
  59.             <param-value>sessionFactory</param-value>    
  60.         </init-param> 
  61.         <init-param>    
  62.             <param-name>singleSession</param-name>    
  63.             <param-value>true</param-value>    
  64.         </init-param> 
  65.         <init-param> 
  66.             <param-name>flushMode</param-name> 
  67.             <param-value>AUTO</param-value> 
  68.         </init-param> 
  69.     </filter> 
  70.     <filter-mapping>    
  71.         <filter-name>openSessionInViewFilter</filter-name>    
  72.         <url-pattern>/*</url-pattern>    
  73.     </filter-mapping> 
  74.       
  75.       
  76.     <!-- encodingFilter --> 
  77.     <filter> 
  78.         <filter-name>Set Character Encoding</filter-name> 
  79.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 
  80.         <init-param> 
  81.             <param-name>encoding</param-name> 
  82.             <param-value>UTF-8</param-value> 
  83.         </init-param> 
  84.         <init-param> 
  85.             <param-name>forceEncoding</param-name> 
  86.             <param-value>true</param-value> 
  87.         </init-param> 
  88.     </filter> 
  89.     <filter-mapping> 
  90.         <filter-name>Set Character Encoding</filter-name> 
  91.         <url-pattern>/*</url-pattern> 
  92.     </filter-mapping> 
  93.       
  94.     <!-- spring filterProxy --> 
  95.     <filter>    
  96.         <filter-name>springSecurityFilterChain</filter-name>    
  97.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  98. </filter>    
  99.     <filter-mapping> 
  100.         <filter-name>springSecurityFilterChain</filter-name> 
  101.         <dispatcher>FORWARD</dispatcher> 
  102.         <dispatcher>REQUEST</dispatcher> 
  103.         <url-pattern>/*</url-pattern> 
  104.     </filter-mapping>   
  105.       
  106. </web-app> 

jsf 配置

  
  
  
  
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <faces-config 
  3.     xmlns="http://java.sun.com/xml/ns/javaee" 
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"  
  7.     version="2.0"> 
  8.       
  9.     <!-- JSF and Spring 整合 --> 
  10.     <application> 
  11.         <el-resolver> 
  12.             org.springframework.web.jsf.el.SpringBeanFacesELResolver  
  13.         </el-resolver>    
  14.     </application> 
  15.      
  16.     <!-- JSF登录异常处理 --> 
  17.     <lifecycle> 
  18.         <phase-listener>com.spring.security.LoginErrorPhaseListener</phase-listener> 
  19.     </lifecycle> 
  20.       
  21. </faces-config> 

applicationContext.xml 配置

  
  
  
  
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.         xmlns:aop="http://www.springframework.org/schema/aop" 
  5.         xmlns:tx="http://www.springframework.org/schema/tx" 
  6.         xmlns:context="http://www.springframework.org/schema/context" 
  7.         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.                             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  9.                             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  10.                             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
  11.     
  12.     <!-- 按类路径自动检测Spring组件,配合使用@Component--> 
  13.     <context:component-scan base-package="com.otv" />
  14.       
  15.     <!-- Beans Declaration --> 
  16.     <bean id="Users" class="com.base.entity.Users"/> 
  17.     <bean id="Roles" class="com.base.entity.Roles"/> 
  18.     <bean id="Resources" class="com.base.entity.Resources"/>
  19.       
  20.     <!-- 基础DAO --> 
  21.     <bean id="baseDao" class="com.base.dao.BaseDao"> 
  22.         <property name="sessionFactory" ref="sessionFactory" /> 
  23.     </bean> 
  24.       
  25.     <!-- 继承DAO基类 parent="baseDao" --> 
  26.     <bean id="resourcesDao" class="com.base.dao.ResourcesDao" parent="baseDao"></bean> 
  27.     <bean id="rolesDao" class="com.base.dao.RolesDao" parent="baseDao"></bean> 
  28.     <bean id="usersDao" class="com.base.dao.UsersDao" parent="baseDao"></bean>
  29.       
  30.     <!--配置数据源--> 
  31.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> 
  32.         <property name="driverClass" value="com.mysql.jdbc.Driver" />     
  33.         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springframe?useUnicode=true&amp;characterEncoding=UTF-8" />   
  34.         <property name="user" value="root" /> 
  35.         <property name="password" value="11111" /> 
  36.         <property name="maxPoolSize" value="30" /> 
  37.         <property name="initialPoolSize" value="10" /> 
  38.         <property name="minPoolSize" value="5" />   
  39.         <property name="maxIdleTime" value="60" /> 
  40.         <property name="maxStatements" value="0" /> 
  41.         <property name="idleConnectionTestPeriod" value="60" /> 
  42.     </bean> 
  43.       
  44.      <!-- 配置SessionFactory --> 
  45.     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
  46.         <property name="dataSource" ref="dataSource" /> 
  47.         <property name="packagesToScan" value="com.base.entity" /> 
  48.         <property name="hibernateProperties"> 
  49.             <props> 
  50.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>   
  51.                 <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
  52. </props> 
  53.         </property> 
  54.     </bean>
  55.       
  56.     <!-- 配置事务管理器 --> 
  57.     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
  58.        <property name="sessionFactory" ref="sessionFactory"/> 
  59.     </bean> 
  60.       
  61.     <!--启动spring注解功能--> 
  62.     <tx:annotation-driven />
  63.       
  64.     <!-- 事务的传播特性 --> 
  65.     <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
  66.         <tx:attributes> 
  67.             <tx:method name="find*" propagation="REQUIRED" read-only="true"/> 
  68.             <tx:method name="getAll*" propagation="REQUIRED" read-only="true"/> 
  69.             <tx:method name="*" propagation="REQUIRED" /> 
  70.         </tx:attributes> 
  71.     </tx:advice> 
  72.     <aop:config proxy-target-class="true"> 
  73.         <aop:pointcut expression="execution(* com.base.dao..*.*(..))" id="daopoint"/> 
  74.         <aop:advisor pointcut-ref="daopoint" advice-ref="txAdvice"/> 
  75.     </aop:config>   
  76.     
  77. </beans> 

applicationContext-security.xml 配置

  
  
  
  
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans:beans xmlns="http://www.springframework.org/schema/security" 
  3.         xmlns:beans="http://www.springframework.org/schema/beans" 
  4.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  5.         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.                             http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 
  7.                   
  8.     <global-method-security pre-post-annotations="enabled" /> 
  9.       
  10.     <http pattern="/login.jsf" security="none" />
  11.       
  12.     <http use-expressions="true" auto-config="true"> 
  13.           
  14.         <form-login login-page="/login.jsf" 
  15.                     login-processing-url="/j_spring_security_check" 
  16.                     default-target-url="/index.jsf" 
  17.                     authentication-failure-url="/login.jsf" /> 
  18.         <logout logout-success-url="/login.jsf" invalidate-session="true" /> 
  19.           
  20.         <remember-me /> 
  21.           
  22.         <!-- session管理 --> 
  23.         <session-management invalid-session-url="/login.jsf"> 
  24.             <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" /> 
  25.         </session-management> 
  26.           
  27.         <!-- FILTER_SECURITY_INTERCEPTOR Spring Security默认的Filter --> 
  28.         <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/>   
  29.     </http> 
  30.       
  31.     <!-- 自定义过滤器 --> 
  32.     <beans:bean id="myFilter" class="com.spring.security.MySecurityFilterInterceptor"> 
  33.         <beans:property name="authenticationManager" ref="authenticationManager" /> 
  34.         <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" /> 
  35.         <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" /> 
  36.     </beans:bean> 
  37.       
  38.     <!-- 配置认证管理器  --> 
  39.     <authentication-manager alias="authenticationManager"> 
  40.         <authentication-provider ref="daoAuthenticationProvider" /> 
  41.     </authentication-manager> 
  42.       
  43.     <beans:bean id="myUserDetailService" class="com.spring.security.MyUserDetailService"> 
  44.         <beans:property name="usersDao" ref="usersDao"></beans:property> 
  45.     </beans:bean> 
  46.       
  47.     <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 --> 
  48.     <beans:bean id="myAccessDecisionManager" class="com.spring.security.MyAccessDecisionManager"></beans:bean> 
  49.       
  50.     <!-- 资源权限关系,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色去访问 --> 
  51.     <beans:bean id="mySecurityMetadataSource" class="com.spring.security.MySecurityMetadataSource"> 
  52.         <beans:constructor-arg name="resourcesDao" ref="resourcesDao"></beans:constructor-arg> 
  53.     </beans:bean> 
  54.       
  55.     <beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> 
  56.         <beans:property name="userDetailsService" ref="myUserDetailService" /> 
  57.         <beans:property name="passwordEncoder" ref="passwordEncoder" /> 
  58.         <beans:property name="saltSource" ref="saltSource" /> 
  59.         <beans:property name="hideUserNotFoundExceptions" value="false" /> 
  60.     </beans:bean> 
  61.       
  62.     <!-- md5密码验证  --> 
  63.     <beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" /> 
  64.     <!-- 加盐值  --> 
  65.     <beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource"> 
  66.         <beans:property name="userPropertyToUse" value="username" /> 
  67.     </beans:bean> 
  68.       
  69. </beans:beans> 

未完待续......

你可能感兴趣的:(java,spring,Hibernate4,security3)