我的一个项目中用到的Spring Security来验证用户合法性,公司里面是连接到LDAP server做验证的,自己又写了一套基于数据库的测试项目,给新手分享一下,也供日后自己回顾。
?
Spring 版本:3.1.0.RELEASE.jar
相关架包可以到官网下载,我用到了下面的架包(LIBS.JPG),有些可能不需要.
?
1. Spring 配置文件中添加:
?
?<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:3307/st?characterEncoding=UTF-8&characterSetResults=UTF-8" />
<property name="user" value="root" />
<property name="password" value="admin" />
<property name="maxPoolSize" value="100" />
<property name="minPoolSize" value="20" />
<property name="initialPoolSize" value="10" />
<property name="maxIdleTime" value="1800" />
<property name="acquireIncrement" value="10" />
<property name="idleConnectionTestPeriod" value="600" />
<property name="acquireRetryAttempts" value="30" />
<property name="breakAfterAcquireFailure" value="false" />
<property name="preferredTestQuery" value="SELECT NOW()" />
</bean>
?
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
?
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
?
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
?
<bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />
?
<sec:http pattern="/admin/css/**" security="none"/>
<sec:http pattern="/admin/img/**" security="none"/>
<sec:http pattern="/admin/js/**" security="none"/>
<sec:http pattern="/login.jsp**" security="none"/>
<sec:http auto-config="true" use-expressions="true">
<sec:form-login login-page="/login.jsp"
default-target-url="/home.spring" login-processing-url="/j_spring_security_check"
authentication-failure-url="/login.jsp?e=1" always-use-default-target="true" />
<sec:logout logout-success-url="/login.jsp" />
<sec:intercept-url pattern="/**" access="hasRole('USER') OR hasRole('ADMIN')" />
<sec:intercept-url pattern="/admin/**" access="hasRole('ADMIN')" />
</sec:http>
?
? ? <sec:authentication-manager> ?
? ? ? ? <sec:authentication-provider ref="MyAuthenticationProvider" /> ?
? ? </sec:authentication-manager> ?
? ??
? ?<bean id="MyAuthenticationProvider" class="com.pro.security.MyAuthenticationProvider">
? ? <property name="jdbcTemplate" ref="jdbcTemplate" />
? ?</bean>
?
?2. Create mysql tables?
?
CREATE TABLE IF NOT EXISTS COM_PRO_USER (`ID` INT(11) NOT NULL AUTO_INCREMENT,`LOGINNAME` VARCHAR (50) NOT NULL,`PASSWORD` VARCHAR (50) NOT NULL,`USERNAME` VARCHAR (50) NOT NULL,PRIMARY KEY (`ID`)) COLLATE='utf8_bin' ENGINE=InnoDB AUTO_INC