CAS 之 Https And Database Authentication

Posted 一盏烛火 孤灯独伴我

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CAS 之 Https And Database Authentication相关的知识,希望对你有一定的参考价值。

CAS 之 Https And Database Authentication(三)

标签(空格分隔): CAS

sso-examples-guides源码


Intro(介绍)

由上节可知Apereo CAS 官方默认使用 https 的方式进行部署:
为了安全,我们使用https方式,并禁用静态账户信息。

What you’ll need(需要掌握)

  • JDK 1.8 or later
  • Maven 3.2+
  • spring boot
  • Spring Tool Suite (STS)
  • IntelliJ IDEA
  • keytool

生成证书

生成key

keytool -genkey -alias ssokeystore  -keyalg RSA -keysize 2048 -keypass 123456 -storepass 123456 -keystore D:/sso/sso.keystore -dname "CN=www.galsang.org,OU=galsang.org,O=galsang,L=Shanghai,ST=Shanghai,C=CN" -ext "san=dns:www.galsang.org,ip:192.168.6.53"

导出证书

keytool -export -file D:/sso/ssokeystore.crt -alias ssokeystore  -keystore D:/sso/sso.keystore  -keypass 123456 -storepass 123456
# 或
keytool -exportcert -alias ssokeystore   -keystore D:/sso/sso.keystore -file D:/sso/ssokeystore.crt -keypass 123456 -storepass 123456

导入证书到本地JDK(客户端认证)

keytool -import -alias ssokeystore   -keystore D:/javaspace/Java/jdk1.8.0_131/jre/lib/security/cacerts -file D:/sso/ssokeystore.crt -keypass changeit -storepass changeit

删除证书

如果之前导入过该别名ssokeystore的证书,则删除证书

keytool -delete -alias ssokeystore   -keystore D:/javaspace/Java/jdk1.8.0_131/jre/lib/security/cacerts -keypass changeit -storepass changeit

查看密钥库证书

keytool -list  -keystore D:/javaspace/Java/jdk1.8.0_131/jre/lib/security/cacerts -keypass changeit -storepass changeit

查看指定证书内容

keytool  -printcert  -file "D:/sso/ssokeystore.crt "

https 配置

步骤一:将生成的密钥 sso.keystore 拷贝至 src/main/resources 目录下
步骤二:进行配置
由于5.2.0版本是默认是开启的,这里先关闭,后期上生产之前再开启并进行配置:
Ticket Granting Cookie

cas:
  tgc:
    secure: false  # cas.tgc.secure=true

步骤三:进行application.yml配置
笔者喜欢使用yml文件的方式进行配置,故将application.properties文件中的配置迁移至application.yml,但依然要保留application.properties文件将原始war中的application.properties文件覆盖,这是因为 maven-war-plugin/overlays的缘故。


spring:
  application:
    name: cas-server
  http:
    encoding:
      enabled: true
      charset: UTF-8
      force: true
  thymeleaf:
    encoding: UTF-8
    cache: true
    mode: html
  aop:
    auto: true
    proxy-target-class: true

# CAS Server Context Configuration
server:
  context-path: /cas
  port: 8443
  max-http-header-size: 2097152
  use-forward-headers: true
  connection-timeout: 20000
  error:
    include-stacktrace: ALWAYS
  compression:
    enabled: true
    mime-types: application/javascript,application/json,application/xml,text/html,text/xml,text/plain
  ssl:
    key-store: classpath:sso.keystore
    key-store-password: 123456
    key-password: 123456
    enabled: true
  tomcat:
    max-http-post-size: 2097152
    basedir: build/tomcat
    max-threads: 10
    port-header: X-Forwarded-Port
    protocol-header: X-Forwarded-Proto
    protocol-header-https-value: https
    remote-ip-header: X-FORWARDED-FOR
    uri-encoding: UTF-8
    accesslog:
      enabled: true
      pattern: "%t %a \'%r\' %s (%D ms)"
      suffix: .log
  session:
    timeout: 300
    cookie:
      http-only: true
    tracking-modes: COOKIE
  context-parameters:
    isLog4jAutoInitializationDisabled: true

cas:
  server:
    name: https://www.galsang.org:8443
    prefix: https://www.galsang.org:8443/cas
  adminPagesSecurity:
    ip: 127.0.0.1
  authn:
    accept:
      users: casuser::Mellon,admin::adminto # 静态用户信息
#  webflow:
#    crypto:
#      enabled: false   #cas.webflow.crypto.enabled=false
  tgc:
    secure: false  # cas.tgc.secure=true

management:
  security:
    enabled: true
    roles: ACTUATOR,ADMIN
    sessions: if_required
  context-path: /status
  add-application-context-header: false

security:
  basic:
    enabled: false
    authorize-mode: role
    path: /cas/status/**

endpoints:
  enabled: false
  sensitive: true
  restart:
    enabled: false
  shutdown:
    enabled: false

logging:
  config: classpath:log4j2.xml

info:
  description: cas-server

Run(运行)

进入cas-server模块执行 build run 命令。

sso-examples-guides\\cas-server>build run

访问入口: https://127.0.0.1:8443/cas/login

运行效果

默认的静态账户信息, 账号:casuser, 密码: Mellon

使用我自定义的静态账户信息, 账号:admin, 密码: adminto

至此,系统可以使用https的形式进行访问,那么下面我们来看一下 Database Authentication是如何配置实现的。


Database Authentication 配置

步骤一: 禁用静态账户

# 禁止静态认证
staticAuthentication: false
# 将将静态账户信息置空
cas:
    authn:
        accept:
          users: 

步骤二: 设计数据库

数据库脚本如下:

DROP DATABASE IF EXISTS `cas_dev`;

CREATE DATABASE `cas_dev` character Set UTF8;

use `cas_dev`;

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `cas_user`
-- ----------------------------
DROP TABLE IF EXISTS `cas_user`;
CREATE TABLE `cas_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of cas_user
-- ----------------------------
INSERT INTO `cas_user` VALUES (\'1\', \'admin\', \'1e1e262780021c6844af137175b56804\');

步骤三: pom.xml文件里增加依赖

        <!--引入数据库认证相关 start-->
        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-support-jdbc</artifactId>
            <version>${cas.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-slf4j-impl</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.zaxxer</groupId>
                    <artifactId>HikariCP</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.driver.version}</version>
        </dependency>
        <!--引入数据库认证相关 end-->

步骤四: 在application.yml中增加相关配置。
最终application.yml内容为:


spring:
  application:
    name: cas-server
  http:
    encoding:
      enabled: true
      charset: UTF-8
      force: true
  thymeleaf:
    encoding: UTF-8
    cache: true
    mode: HTML
  aop:
    auto: true
    proxy-target-class: true

# CAS Server Context Configuration
server:
  context-path: /cas
  port: 8443
  max-http-header-size: 2097152
  use-forward-headers: true
  connection-timeout: 20000
  error:
    include-stacktrace: ALWAYS
  compression:
    enabled: true
    mime-types: application/javascript,application/json,application/xml,text/html,text/xml,text/plain
  ssl:
    key-store: classpath:sso.keystore
    key-store-password: 123456
    key-password: 123456
    enabled: true
  tomcat:
    max-http-post-size: 2097152
    basedir: build/tomcat
    max-threads: 10
    port-header: X-Forwarded-Port
    protocol-header: X-Forwarded-Proto
    protocol-header-https-value: https
    remote-ip-header: X-FORWARDED-FOR
    uri-encoding: UTF-8
    accesslog:
      enabled: true
      pattern: "%t %a \'%r\' %s (%D ms)"
      suffix: .log
  session:
    timeout: 300
    cookie:
      http-only: true
    tracking-modes: COOKIE
  context-parameters:
    isLog4jAutoInitializationDisabled: true

cas:
  server:
    name: https://www.galsang.org:8443
    prefix: https://www.galsang.org:8443/cas
  adminPagesSecurity:
    ip: 127.0.0.1
  tgc:
    secure: false  # cas.tgc.secure=true
  authn:
    accept:
      users:   # 静态用户信息 casuser::Mellon,admin::adminto
    jdbc:
      query[0]:
        sql: select * from cas_user where username=?
        healthQuery: select 1
        isolateInternalQueries: false
        # 指定时区 serverTimezone=Asia/Shanghai
        url: jdbc:mysql://127.0.0.1:3306/cas_dev?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false
        failFast: true
        isolationLevelName: ISOLATION_READ_COMMITTED
        dialect: org.hibernate.dialect.MySQLDialect
        leakThreshold: 10
        propagationBehaviorName: PROPAGATION_REQUIRED
        batchSize: 1
        user: root
        password: adminto
        autocommit: false
        maxAgeDays: 180
        driverClass: com.mysql.cj.jdbc.Driver
        idleTimeout: 5000
        fieldPassword: password
        passwordEncoder:
          type: DEFAULT
          characterEncoding: UTF-8
          encodingAlgorithm: MD5

staticAuthentication: false

management:
  security:
    enabled: true
    roles: ACTUATOR,ADMIN
    sessions: if_required
  context-path: /status
  add-application-context-header: false

security:
  basic:
    enabled: false
    authorize-mode: role
    path: /cas/status/**

endpoints:
  enabled: false
  sensitive: true
  restart:
    enabled: false
  shutdown:
    enabled: false

logging:
  config: classpath:log4j2.xml

info:
  description: cas-server
  

Run(运行)

进入cas-server模块执行 build run 命令。

sso-examples-guides\\cas-server>build run

访问入口: https://127.0.0.1:8443/cas/login

使用数据库中默认的账户信息, 账号:admin, 密码: adminto

密码修改可以在src/test/java 目录下的 PasswordByMD5Main类进行重置密码,并更新到数据库即可。

至此,系统可以使用https的形式进行访问,并通过 Database Authentication进行用户认证。

Conclusions(结论)

  • Database Authentication 使用的是JPA方式,数据库连接池使用的是HikariCP
  • JPA是默认的 Database Authentication 方式,那么在后面的文章中将说明如何替换JPA

Recommendations(建议)

  • 使用https
  • 禁用静态账户
  • 工程复杂,一定要注意版本之间的关系,开源项目,最好对照源码编译版本进行部署。

原创声明

作者:随风浮云
出处:http://www.cnblogs.com/ljmatlight
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明。
文中有不妥或者错误的地方,欢迎勘误,如果你有更好的建议,可以给我留言讨论,共同进步。
互联网技术时效性较强,引用请慎重。


以上是关于CAS 之 Https And Database Authentication的主要内容,如果未能解决你的问题,请参考以下文章

CAS Server and Client - https

CAS Server and Client - https

CAS Server and Client - https

CAS Server and Client - http

CAS Server and Client - http

CAS Server and Client - http