关于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中运行即可):
用户表users
- -- ----------------------------
- -- Table structure for `users`
- -- ----------------------------
- DROP TABLE IF EXISTS `users`;
- CREATE TABLE `users` (
- `ID` int(11) NOT NULL,
- `ACCOUNT` varchar(50) DEFAULT NULL,
- `ENABLE` int(11) DEFAULT NULL,
- `PASSWORD` varchar(50) DEFAULT NULL,
- PRIMARY KEY (`ID`),
- UNIQUE KEY `ID` (`ID`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of users
- -- ----------------------------
- INSERT INTO `users` VALUES ('100', 'admin', '1', 'ceb4f32325eda6142bd65215f4c0f371');
- INSERT INTO `users` VALUES ('101', 'user', '1', '47a733d60998c719cf3526ae7d106d13');
- INSERT INTO `users` VALUES ('102', 'u', '1', 'deeb9de5f0ad8e12b8f7fe7e0e318d76');
- INSERT INTO `users` VALUES ('103', 'u1', '1', '76366d239fe64a4d5b9d9c07446e7764');
角色表roles
- -- ----------------------------
- -- Table structure for `roles`
- -- ----------------------------
- DROP TABLE IF EXISTS `roles`;
- CREATE TABLE `roles` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(255) DEFAULT NULL,
- `enable` int(11) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=MyISAM AUTO_INCREMENT=202 DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of roles
- -- ----------------------------
- INSERT INTO `roles` VALUES ('200', 'ROLE_ADMIN', '1');
- INSERT INTO `roles` VALUES ('201', 'ROLE_USER', '1');
资源表resources
- -- ----------------------------
- -- Table structure for `resources`
- -- ----------------------------
- DROP TABLE IF EXISTS `resources`;
- CREATE TABLE `resources` (
- `ID` varchar(255) NOT NULL,
- `MEMO` longtext,
- `NAME` varchar(50) DEFAULT NULL,
- `PRIORITY` int(11) DEFAULT NULL,
- `TYPE` varchar(11) DEFAULT NULL,
- `URL` longtext,
- PRIMARY KEY (`ID`),
- UNIQUE KEY `ID` (`ID`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of resources
- -- ----------------------------
- INSERT INTO `resources` VALUES ('400', null, 'index', '1', 'URL', '/index.jsf');
- INSERT INTO `resources` VALUES ('401', null, 'admin', '1', 'URL', '/admin.jsf');
- INSERT INTO `resources` VALUES ('402', null, 'index1', '1', 'URL', '/index2.jsf');
用户角色中间表users_roles
- -- ----------------------------
- -- Table structure for `users_roles`
- -- ----------------------------
- DROP TABLE IF EXISTS `users_roles`;
- CREATE TABLE `users_roles` (
- `uid` int(11) NOT NULL,
- `rid` int(11) NOT NULL,
- PRIMARY KEY (`uid`,`rid`),
- KEY `FKF6CCD9C6CBF0213D` (`uid`),
- KEY `FKF6CCD9C6CBC416AF` (`rid`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of users_roles
- -- ----------------------------
- INSERT INTO `users_roles` VALUES ('100', '200');
- INSERT INTO `users_roles` VALUES ('100', '201');
- INSERT INTO `users_roles` VALUES ('101', '201');
- INSERT INTO `users_roles` VALUES ('102', '201');
- INSERT INTO `users_roles` VALUES ('103', '201');
角色资源中间表roles_resources
- -- ----------------------------
- -- Table structure for `roles_resources`
- -- ----------------------------
- DROP TABLE IF EXISTS `roles_resources`;
- CREATE TABLE `roles_resources` (
- `rid` int(11) NOT NULL,
- `rsid` varchar(255) NOT NULL,
- PRIMARY KEY (`rsid`,`rid`),
- KEY `FKAF06BF23CBC416AF` (`rid`),
- KEY `FKAF06BF23B74E21A6` (`rsid`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of roles_resources
- -- ----------------------------
- INSERT INTO `roles_resources` VALUES ('200', '400');
- INSERT INTO `roles_resources` VALUES ('201', '400');
- INSERT INTO `roles_resources` VALUES ('200', '401');
- INSERT INTO `roles_resources` VALUES ('200', '402');
- INSERT INTO `roles_resources` VALUES ('201', '402');
二、web工程
eclipse下New->Dynamic Web project,输入工程名jweb-spring->Finish
1. xml 配置文件:
web.xml 配置
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- id="WebApp_ID" version="2.5">
- <context-param>
- <description>JSF状态保存在客户端</description>
- <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
- <param-value>client</param-value>
- </context-param>
- <!-- JSF2.0的模式配置,开发模式下会在调试时报更加详细的错误-->
- <context-param>
- <param-name>javax.faces.PROJECT_STAGE</param-name>
- <param-value>Development</param-value>
- </context-param>
- <context-param>
- <param-name>javax.faces.CONFIG_FILES</param-name>
- <param-value>/WEB-INF/faces-config.xml</param-value>
- </context-param>
- <!-- JSF2.0的配置-->
- <servlet>
- <servlet-name>Faces Servlet</servlet-name>
- <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>Faces Servlet</servlet-name>
- <url-pattern>*.jsf</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>Faces Servlet</servlet-name>
- <url-pattern>*.faces</url-pattern>
- </servlet-mapping>
- <!-- Spring ContextLocation -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/applicationContext*.xml</param-value>
- </context-param>
- <!-- spring启动监听器 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <listener>
- <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
- </listener>
- <welcome-file-list>
- <welcome-file>/index.xhtml</welcome-file>
- </welcome-file-list>
- <!-- 解决Hibernate的延迟加载造成的Session提前关闭问题,设置该项使Session保持Request请求完成才关闭Session -->
- <filter>
- <filter-name>openSessionInViewFilter</filter-name>
- <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
- <init-param>
- <param-name>sessionFactoryBeanName</param-name>
- <param-value>sessionFactory</param-value>
- </init-param>
- <init-param>
- <param-name>singleSession</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>flushMode</param-name>
- <param-value>AUTO</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>openSessionInViewFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- encodingFilter -->
- <filter>
- <filter-name>Set Character Encoding</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>Set Character Encoding</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- spring filterProxy -->
- <filter>
- <filter-name>springSecurityFilterChain</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>springSecurityFilterChain</filter-name>
- <dispatcher>FORWARD</dispatcher>
- <dispatcher>REQUEST</dispatcher>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
jsf 配置
- <?xml version="1.0" encoding="UTF-8"?>
- <faces-config
- 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-facesconfig_2_0.xsd"
- version="2.0">
- <!-- JSF and Spring 整合 -->
- <application>
- <el-resolver>
- org.springframework.web.jsf.el.SpringBeanFacesELResolver
- </el-resolver>
- </application>
- <!-- JSF登录异常处理 -->
- <lifecycle>
- <phase-listener>com.spring.security.LoginErrorPhaseListener</phase-listener>
- </lifecycle>
- </faces-config>
applicationContext.xml 配置
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- 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/tx http://www.springframework.org/schema/tx/spring-tx-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <!-- 按类路径自动检测Spring组件,配合使用@Component-->
- <context:component-scan base-package="com.otv" />
- <!-- Beans Declaration -->
- <bean id="Users" class="com.base.entity.Users"/>
- <bean id="Roles" class="com.base.entity.Roles"/>
- <bean id="Resources" class="com.base.entity.Resources"/>
- <!-- 基础DAO -->
- <bean id="baseDao" class="com.base.dao.BaseDao">
- <property name="sessionFactory" ref="sessionFactory" />
- </bean>
- <!-- 继承DAO基类 parent="baseDao" -->
- <bean id="resourcesDao" class="com.base.dao.ResourcesDao" parent="baseDao"></bean>
- <bean id="rolesDao" class="com.base.dao.RolesDao" parent="baseDao"></bean>
- <bean id="usersDao" class="com.base.dao.UsersDao" parent="baseDao"></bean>
- <!--配置数据源-->
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
- <property name="driverClass" value="com.mysql.jdbc.Driver" />
- <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springframe?useUnicode=true&characterEncoding=UTF-8" />
- <property name="user" value="root" />
- <property name="password" value="11111" />
- <property name="maxPoolSize" value="30" />
- <property name="initialPoolSize" value="10" />
- <property name="minPoolSize" value="5" />
- <property name="maxIdleTime" value="60" />
- <property name="maxStatements" value="0" />
- <property name="idleConnectionTestPeriod" value="60" />
- </bean>
- <!-- 配置SessionFactory -->
- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <property name="packagesToScan" value="com.base.entity" />
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
- <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
- </props>
- </property>
- </bean>
- <!-- 配置事务管理器 -->
- <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory"/>
- </bean>
- <!--启动spring注解功能-->
- <tx:annotation-driven />
- <!-- 事务的传播特性 -->
- <tx:advice id="txAdvice" transaction-manager="transactionManager">
- <tx:attributes>
- <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
- <tx:method name="getAll*" propagation="REQUIRED" read-only="true"/>
- <tx:method name="*" propagation="REQUIRED" />
- </tx:attributes>
- </tx:advice>
- <aop:config proxy-target-class="true">
- <aop:pointcut expression="execution(* com.base.dao..*.*(..))" id="daopoint"/>
- <aop:advisor pointcut-ref="daopoint" advice-ref="txAdvice"/>
- </aop:config>
- </beans>
applicationContext-security.xml 配置
- <?xml version="1.0" encoding="UTF-8"?>
- <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-3.0.xsd
- http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
- <global-method-security pre-post-annotations="enabled" />
- <http pattern="/login.jsf" security="none" />
- <http use-expressions="true" auto-config="true">
- <form-login login-page="/login.jsf"
- login-processing-url="/j_spring_security_check"
- default-target-url="/index.jsf"
- authentication-failure-url="/login.jsf" />
- <logout logout-success-url="/login.jsf" invalidate-session="true" />
- <remember-me />
- <!-- session管理 -->
- <session-management invalid-session-url="/login.jsf">
- <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" />
- </session-management>
- <!-- FILTER_SECURITY_INTERCEPTOR Spring Security默认的Filter -->
- <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
- </http>
- <!-- 自定义过滤器 -->
- <beans:bean id="myFilter" class="com.spring.security.MySecurityFilterInterceptor">
- <beans:property name="authenticationManager" ref="authenticationManager" />
- <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
- <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
- </beans:bean>
- <!-- 配置认证管理器 -->
- <authentication-manager alias="authenticationManager">
- <authentication-provider ref="daoAuthenticationProvider" />
- </authentication-manager>
- <beans:bean id="myUserDetailService" class="com.spring.security.MyUserDetailService">
- <beans:property name="usersDao" ref="usersDao"></beans:property>
- </beans:bean>
- <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->
- <beans:bean id="myAccessDecisionManager" class="com.spring.security.MyAccessDecisionManager"></beans:bean>
- <!-- 资源权限关系,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色去访问 -->
- <beans:bean id="mySecurityMetadataSource" class="com.spring.security.MySecurityMetadataSource">
- <beans:constructor-arg name="resourcesDao" ref="resourcesDao"></beans:constructor-arg>
- </beans:bean>
- <beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
- <beans:property name="userDetailsService" ref="myUserDetailService" />
- <beans:property name="passwordEncoder" ref="passwordEncoder" />
- <beans:property name="saltSource" ref="saltSource" />
- <beans:property name="hideUserNotFoundExceptions" value="false" />
- </beans:bean>
- <!-- md5密码验证 -->
- <beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
- <!-- 加盐值 -->
- <beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
- <beans:property name="userPropertyToUse" value="username" />
- </beans:bean>
- </beans:beans>
未完待续......