前言
正式使用cas,我们不能继续从配置文件中读取配置信息,需要从数据库中读取信息来进行用户验证。
创建用户表,并插入数据
CREATE TABLE `t_user` ( `id` bigint(15) NOT NULL COMMENT'主键', `account` varchar(30) DEFAULT NULL COMMENT'账号', `password` varchar(255) DEFAULT NULL COMMENT'密码', `valid` tinyint(1) DEFAULT NULL COMMENT '是否有效', PRIMARY KEY(`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;zhangsan MD5 加密后为01d7f40760960e7bd9443513f22ab9af
insert into `t_user`(`id`,`account`,`password`,`valid`) values (25019377879351297,'zhangsan','01d7f40760960e7bd9443513f22ab9af',1);
配置cas服务端
2.1 pom.xml 加入cas-server-support-jdbc 和 mysql-connector-java的jar包
注意:本来还依赖其他jar包的(比如c3p0等),但是4.2.7的cas服务端其他jar包都有了,在本例中之需要添加上面两个包即可。
2.2 修改deployerConfigContext.xml
第一步
注释掉原来的acceptUsersAuthenticationHandler配置
第二步
新增配置
<!--begin 从数据库中的用户表中读取 --> <bean id="MD5PasswordEncoder" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder" autowire="byName"> <constructor-arg value="MD5" /> </bean> <bean id="queryDatabaseAuthenticationHandler" name="primaryAuthenticationHandler" class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler"> <property name="passwordEncoder" ref="MD5PasswordEncoder" /> </bean> <alias name="dataSource" alias="queryDatabaseDataSource"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" p:driverClass="com.mysql.jdbc.Driver" p:jdbcUrl="jdbc:mysql://172.16.30.34:3306/sso?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull" p:user="root" p:password="root" p:initialPoolSize="6" p:minPoolSize="6" p:maxPoolSize="18" p:maxIdleTimeExcessConnections="120" p:checkoutTimeout="10000" p:acquireIncrement="6" p:acquireRetryAttempts="5" p:acquireRetryDelay="2000" p:idleConnectionTestPeriod="30" p:preferredTestQuery="select 1"/> <!--end 从数据库中的用户表中读取 -->
注意:上面需要新增的配置可以直接拷贝到你的该文件中,然后修改数据库连接串中的ip地址,数据库名称,登录账号和密码
2.3、修改cas.properties
cas4.2系列很多配置都改在了cas.properties里面了,本例中需要修改该文件。
增加配置:
cas.jdbc.authn.query.sql=select password from t_user where account=? and valid=true
注意:该SQL可以自己修改只要能根据账号查询出对应的密码字段即可,至于你的这些字段叫啥名字都没关系。
3、测试
重新打包,放入tomcat中,用户名:zhangsan 密码:zhangsan 显示登录成功
注意:加密算法也可以不用md5,jeesite框架的密码是散列并且加盐,所以我们校验规格那里需要修改,以下内容就是兼容jeesite的登录验证规格。
4.自定义登录验证(加密规则)
注意:我的项目是基于jeesite的,所以jeesite加密相关的类我copy过来了,但是以下内容适用于所有项目。
4.1 new Source Folder
src/main/java 和 src/main/test
4.2 修改deployerConfigContext.xml
queryDatabaseAuthenticationHandler的实现由org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler
改为了com.mryx.cas.authentication.handler.MryxQueryDatabaseAuthenticationHandler
MryxQueryDatabaseAuthenticationHandler 具体代码实现为
package com.mryx.cas.authentication.handler; import org.apache.commons.lang3.StringUtils; import org.jasig.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler; import org.jasig.cas.authentication.HandlerResult; import org.jasig.cas.authentication.PreventedException; import org.jasig.cas.authentication.UsernamePasswordCredential; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.stereotype.Component; import javax.security.auth.login.AccountNotFoundException; import javax.security.auth.login.FailedLoginException; import javax.sql.DataSource; import javax.validation.constraints.NotNull; import java.security.GeneralSecurityException; /** * 重写了cas的用户名密码验证处理类 * @author tanlk */ @Component("mryxQueryDatabaseAuthenticationHandler") public class MryxQueryDatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler { @NotNull private String sql; @Override protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException { if (StringUtils.isBlank(this.sql) || getJdbcTemplate() == null) { throw new GeneralSecurityException("Authentication handler is not configured correctly"); } final String username = credential.getUsername(); //final String encryptedPassword = this.getPasswordEncoder().encode(credential.getPassword()); try { final String dbPassword = getJdbcTemplate().queryForObject(this.sql, String.class, username); //主要修改了这个地方,加入了自己的验证密码逻辑 if (!CheckPassword.validatePassword(credential.getPassword(), dbPassword)) { throw new FailedLoginException("Password does not match value on record."); } } catch (final IncorrectResultSizeDataAccessException e) { if (e.getActualSize() == 0) { throw new AccountNotFoundException(username + " not found with SQL query"); } else { throw new FailedLoginException("Multiple records found for " + username); } } catch (final DataAccessException e) { throw new PreventedException("SQL exception while executing query for " + username, e); } return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null); } /** * @param sql The sql to set. */ @Autowired public void setSql(@Value("${cas.jdbc.authn.query.sql:}") final String sql) { this.sql = sql; } @Override @Autowired(required = false) public void setDataSource(@Qualifier("queryDatabaseDataSource") final DataSource dataSource) { super.setDataSource(dataSource); } }
重新编译部署项目,至此完成Jeesite单点登录cas自定义登录验证