首先使用官网推荐的方法:git clone https://github.com/apereo/cas-overlay-template/tree/4.2,我这里用的是4.2版本,因为他是maven构建的,5以上的版本是gradle构建的,我对gradle没有maven熟练。

clone完成,导入我们的idea里,mvn clean install 开始下载jar包。下载完成之后,我们的工程是这样子的。

spring boot pfx证书 spring boot license授权_sql

首先我们先看

WEB-INF/spring-configuration/propertyFileConfigurer.xml 这个文件,把里面的

<util:properties id="casProperties" location="file:/etc/cas/cas.properties" />

改为(根据你的项目路径而定)

<util:properties id="casProperties" location="file:D:\beijing\project\my\cas-overlay-template-4.2\etc\cas.properties" />

然后我们mvn clean package,打个war包,放在tomcat里的webapps下面,启动tomcat,输入https://sso.maple.com:8443/cas,即可看到登录页面

spring boot pfx证书 spring boot license授权_bc_02

 输入默认的账密:casuser/Mellon,即可登录成功

spring boot pfx证书 spring boot license授权_sql_03

 输入https://sso.maple.com:8443/cas/logout登出

spring boot pfx证书 spring boot license授权_spring_04

再次输入https://sso.maple.com:8443/cas/,还是会跳到登录页面

spring boot pfx证书 spring boot license授权_sql_05

到此为止,我们的工程都是OK的,下面开始集成我们的数据库。

--------------------------------------------------------优雅的分割线-----------------------------------------------------------------

一、建库(sso),建表(user),插入初始化数据

CREATE TABLE `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;
INSERT INTO `sso`.`user` (`id`, `account`, `password`, `valid`) VALUES ('1', 'zhangsan', '01d7f40760960e7bd9443513f22ab9af', '1');

 

二、引入pom

<dependency>
            <groupId>org.jasig.cas</groupId>
            <artifactId>cas-server-support-jdbc</artifactId>
            <version>${cas.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.31</version>
            <scope>runtime</scope>
        </dependency>

三、修改deployerConfigContext.xml文件

修改 D:\beijing\project\my\cas-overlay-template-4.2\target\war\work\org.jasig.cas\cas-server-webapp\WEB-INF\deployerConfigContext.xml 这个文件

1、把 

<alias name="acceptUsersAuthenticationHandler" alias="primaryAuthenticationHandler" />

注释掉

2、新增以下配置

<!--begin 从数据库中的用户表中读取 -->
    <bean id="MD5PasswordEncoder"
          class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder"
          autowire="byName">
        <constructor-arg value="MD5" />
    </bean>

    <bean id="queryDatabaseAuthenticationHandler" name="databaseAuthenticationHandler"
          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://106.15.184.65:3306/sso"
            p:user="root"
            p:password="8UNG3dp"
            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  从数据库中的用户表中读取 -->

3、把 

<entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />

改为

<entry key-ref="databaseAuthenticationHandler" value-ref="primaryPrincipalResolver" />

四、修改cas.properties文件

把 etc/cas.properties 里面的 cas.jdbc.authn.query.sql 前面的注释去掉,加上 

SELECT password from user where account = ? and valid = true

五、打war包,放进tomcat里的webapps,启动tomcat,输入https://sso.maple.com:8443/cas,使用 zhangsan/zhangsan 登录

 

spring boot pfx证书 spring boot license授权_spring boot pfx证书_06

 

spring boot pfx证书 spring boot license授权_bc_07

 OK,那到这里我们就集成完数据库了。

--------------------------------------------------------优雅的分割线-----------------------------------------------------------------

有的同学想说,我们数据库里存的还有盐值呢,一般密码字段存的是  Sha256/MD5(password+salt) 这样子的加密算法,这样就不用默认的加密算法,且还要把 salt 值给查询出来。我们先看一下 目前所使用的QueryDatabaseAuthenticationHandler里面是怎么处理的。

@Component("queryDatabaseAuthenticationHandler")
public class QueryDatabaseAuthenticationHandler 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 (!dbPassword.equals(encryptedPassword)) {
                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);
    }
}

那我们模仿着这个类写一下,

1、我在这里新增了一个我自己的类

spring boot pfx证书 spring boot license授权_sql_08


 代码内容为:

package handler;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
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;

/**
 * @Description 一般项目中,user表会有个salt盐值,DB里存的密码 = Sha256/MD5(password + salt)
 * @Date 2020/4/18 15:08
 * @Created by 王弘博
 */
@Component("myQueryDatabaseAuthenticationHandler")
public class MyQueryDatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {

    @NotNull
    private String sql;

    @NotNull
    private String saltSql;

    @Override
    protected HandlerResult authenticateUsernamePasswordInternal(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 {

            //查询DB里存的密码
            final String dbPassword = getJdbcTemplate().queryForObject(this.sql, String.class, username);

            //查询DB里存的盐值
            final String dbSalt = getJdbcTemplate().queryForObject(this.saltSql, String.class, username);

            String encryptedPassword = new Md5Hash(credential.getPassword(), dbSalt, 1024).toHex();

            //加密(用户输入的+salt) 和 DB里存的 进行比较
            if (!dbPassword.equals(encryptedPassword)) {

                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;
    }

    /**
     * @param saltSql The saltSql to set.
     */
    @Autowired
    public void setSaltSql(@Value("${cas.jdbc.authn.query.salt.sql:}") final String saltSql) {
        this.saltSql = saltSql;
    }

    @Override
    @Autowired(required = false)
    public void setDataSource(@Qualifier("queryDatabaseDataSource") final DataSource dataSource) {
        super.setDataSource(dataSource);
    }

    public static void main(String[] args) {
        String encryptedPassword = new Md5Hash("zhangsan", "123456", 1024).toHex();
        System.out.println(encryptedPassword);

    }
}

关键代码是 

String encryptedPassword = new Md5Hash(credential.getPassword(), dbSalt, 1024).toHex();


 


2、然后 deployerConfigContext.xml 这里的配置需要改一下


spring boot pfx证书 spring boot license授权_spring_09

 3、cas.properties 文件,新增一条获取 salt 的sql

spring boot pfx证书 spring boot license授权_spring boot pfx证书_10

4、计算加密后的密码。密码:zhangsan,盐值:123456,Md5加密次数是1024之后得出来的密码为:d329571893ea0e41a3718a568a10794f

spring boot pfx证书 spring boot license授权_sql_11

5、我们修改表结构,和初始化数据


CREATE TABLE `user` (
  `id` bigint(15) NOT NULL COMMENT '主键',
  `account` varchar(30) DEFAULT NULL COMMENT '账号',
  `password` varchar(255) DEFAULT NULL COMMENT '密码',
  `salt` varchar(16) DEFAULT NULL COMMENT '盐',
  `valid` tinyint(1) DEFAULT NULL COMMENT '是否有效',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO `sso`.`user` (`id`, `account`, `password`, `salt`, `valid`) VALUES ('1', 'zhangsan', 'd329571893ea0e41a3718a568a10794f', '123456', '1');


6、打war包,放进tomcat的webapps,测试登录正常

spring boot pfx证书 spring boot license授权_spring boot pfx证书_12

这样我们就可以自定义自己的加密规则了,不论是Sha,还是Hash,Md5,都是一样的思路。

OK,那今天的 cas-server 集成 数据库,就结束了,下篇文章我们将模仿实际项目,来测试 SSO 单点登录