【CAS學習之二】部署CAS服務端


環境
  apache-tomcat-8.5.45
  cas:5.2.6

一、部署CAS
1、部署war包
將上一篇文章中構建生成的cas.war放到tomcat/webapps下
2、啟動tomcat並訪問 (官方的基礎版本中配置了一個用戶 casuser/Mellon)
2.1 CAS項目要求用https連接,如果使用http也行,也能登錄成功,只是會提示不安全
訪問連接:http://localhost:8080/cas

2.2 去除HTTPS
(1)修改WEB-INF/classess/application.properties,添加以下配置

#去除https驗證
cas.tgc.secure=false
#注冊Services中的JSON驗證
cas.serviceRegistry.initFromJson=true

(2)修改WEB-INF/classess/services/HTTPSandIMAPS-10000001.json
注冊哪些客戶端可以訪問認證中心

{
  "@class" : "org.apereo.cas.services.RegexRegisteredService",
  "serviceId" : "^(https|imaps|http)://.*",
  "name" : "HTTPS and IMAPS",
  "id" : 10000001,
  "description" : "This service definition authorizes all application urls that support HTTPS and IMAPS protocols.",
  "evaluationOrder" : 10000
  "proxyPolicy" : {
    "@class" : "org.jasig.cas.services.RegexMatchingRegisteredServiceProxyPolicy",
    "pattern" : "^(https|imaps|http)://.*" }
}

(3)如果客戶端之前做過https配置,需要從客戶端jre的證書倉庫中刪掉之前為做HTTPS單點登錄加的那個證書

keytool -delete -alias cas -keystore  C:/Java/jdk1.8.0_91/jre/lib/security/cacerts

參考:去除HTTPS   和  配置使用HTTP協議訪問的服務端  

2.3 使用https連接,需要先生成https的加密密匙,用jdk自帶的keytool就行。

(1)使用jdk生成https證書
JDK中keytool是一個證書管理工具,可以生成自簽名證書。 就是自己生成的證書,並不是官方生成的證書。除非是很正式的項目,否則使用自己簽發的證書即可,因為官方生成證書是要花錢滴
命令解釋

keytool 
-genkey 
-alias cas(別名) 
-keypass 123456(別名密碼) 
-keyalg RSA(生證書的算法名稱,RSA是一種非對稱加密算法) 
-keysize 1024(密鑰長度,證書大小) 
-validity 365(證書有效期,天單位) 
-keystore E:/cas/keystore/cas.keystore(指定生成證書的位置和證書名稱) 
-storepass 123456(獲取keystore信息的密碼)
- storetype (指定密鑰倉庫類型) 
-dname 
"CN=cas.example.org,(您的名字與姓氏是什么?)
OU=example.com,(您的組織單位名稱是什么?)
O=cas,(您的組織名稱是什么?)
L=Shenzhen,(您所在的城市或區域名稱是什么?)
ST=Shenzhen,(您所在的省/市/自治區名稱是什么?)
C=CN"(該單位的雙字母國家/地區代碼是什么?)

進入jdk的bin目錄下面,打開CMD命令行工具,執行命令:

keytool -genkey -alias cas -keyalg RSA -keysize 2048 -keypass 123456 -storepass 123456 -keystore E:/cas/keystore/cas.keystore -dname "CN=cas.example.org,OU=example.com,O=cas,L=Jinan,ST=Jinan,C=CN"

關於jdk證書,請參考:

使用JDK自帶工具keytool生成ssl證書

(2)同時需要修改 tomcat 的配置文件 server.xml,把加密密匙的相關配置寫進去。

    <!-- 去掉 http 訪問 8080 端口 -->
  <!-- <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
--> <!-- 用 https 訪問 8443 端口 --> <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" maxThreads="200" scheme="https" secure="true" SSLEnabled="true" keystoreFile="E:/cas/keystore/cas.keystore" keystorePass="123456" clientAuth="false" sslProtocol="TLS"/>

修改完成后 重啟Tomcat

(3)訪問,用戶 casuser/Mellon
訪問連接:https://localhost:8443/cas

 

二、改用數據庫驗證用戶名和密碼
先來搞清楚application.properties配置文件中各個屬性含義,請參考:application.properties

0、本地搭建一個mysql,創建一個數據庫castest,新建一個表:cms_auth_user


1、我們這里要拷貝cas.war解壓出來的一份cas\WEB-INF\classes\application.properties放到cas-overlay-template\src\main\resources\application.properties,然后作如下修改

##
# CAS Server Context Configuration
#
server.context-path=/cas
server.port=8443
# 這些放在services目錄的json文件來注冊服務了,
# 先說一下這里的“服務” 其實指的就是客戶端,更准確的說就是它的url,如果一個客戶端沒有注冊到CAS的服務列表,
# 那么你通過客戶端跳轉到CAS,CAS會拒絕這個跳轉。
# war包解壓出來的services里已經有了兩個json文件,其中HTTPSandIMAPS-100xxxxxx.json中有一段:
# "serviceId" : "^(https|imaps|http)://.*",
# 后邊這部分是個正則表達式,為了支持http協議的客戶端,我在里面加了個http,代表所有URL符合這個正則表達式的服務都會被當成已經注冊的服務
cas.serviceRegistry.initFromJson=true #STEP 簽發證書,如果是用spring boot之類嵌入式的容器,則需要改這里的配置,如果是直接部在tomcat中,則需要把tomcat改成https的 #server.ssl.key-store=file:/etc/cas/thekeystore
#server.ssl.key-store-password=changeit
#server.ssl.key-password=changeit
# server.ssl.ciphers=
# server.ssl.client-auth=
# server.ssl.enabled=
# server.ssl.key-alias=
# server.ssl.key-store-provider=
# server.ssl.key-store-type=
# server.ssl.protocol=
# server.ssl.trust-store=
# server.ssl.trust-store-password=
# server.ssl.trust-store-provider=
# server.ssl.trust-store-type=

server.max-http-header-size=2097152
server.use-forward-headers=true
server.connection-timeout=20000
server.error.include-stacktrace=ALWAYS

server.compression.enabled=true
server.compression.mime-types=application/javascript,application/json,application/xml,text/html,text/xml,text/plain

server.tomcat.max-http-post-size=2097152
server.tomcat.basedir=build/tomcat
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms)
server.tomcat.accesslog.suffix=.log
server.tomcat.max-threads=10
server.tomcat.port-header=X-Forwarded-Port
server.tomcat.protocol-header=X-Forwarded-Proto
server.tomcat.protocol-header-https-value=https
server.tomcat.remote-ip-header=X-FORWARDED-FOR
server.tomcat.uri-encoding=UTF-8

spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true

##
# CAS Cloud Bus Configuration
#
spring.cloud.bus.enabled=false
# spring.cloud.bus.refresh.enabled=true
# spring.cloud.bus.env.enabled=true
# spring.cloud.bus.destination=CasCloudBus
# spring.cloud.bus.ack.enabled=true

endpoints.enabled=false
endpoints.sensitive=true

endpoints.restart.enabled=false
endpoints.shutdown.enabled=false

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

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

##
# CAS Web Application Session Configuration
#
server.session.timeout=300
server.session.cookie.http-only=true
server.session.tracking-modes=COOKIE

##
# CAS Thymeleaf View Configuration
#
spring.thymeleaf.encoding=UTF-8

#這個配置沒有在官網找到說明,是自己摸索出來的,服務端的HTML頁面使用的是thymeleaf編寫(http://www.ultraq.net.nz/thymeleaf/layout)
#thymeleaf默認會在啟動的時候就把頁面的靜態內容給放到緩存里,這給我修改CAS默認登錄頁帶來了很大的麻煩,每次修改一點點頁面內容,刷新是看不到效果的,只得重啟服務,為了方便開發,
#我把這個配置設成false,就是說不要緩存。
#
#如果你也想修改登錄頁這里給出幾個建議:
#1、如果不懂thyeleaf先簡單了解一下thymeleaf官網的demo寫法;
#2、登錄頁的模板是layout.html,其中有幾個js是從谷歌CDN上下載的,而谷歌我們國內又訪問不了,
#這就會導致登錄頁加載非常慢,建議先把這幾個js本地化;
#3、登錄頁主要是casLoginView.html和fragments目錄下的loginform.html;
#4、layout.html引入了好幾個類似logo.html,footer.html的頁面,這幾個頁面看名字就知道干什么的,建議對他們進行修改,改成自己的
spring.thymeleaf.cache=true
spring.thymeleaf.mode=HTML
##
# CAS Log4j Configuration
#
# logging.config=file:/etc/cas/log4j2.xml
server.context-parameters.isLog4jAutoInitializationDisabled=true

##
# CAS AspectJ Configuration
#
spring.aop.auto=true
spring.aop.proxy-target-class=true

##
# CAS Authentication Credentials
#
# 注釋掉寫死的用戶 改用jdbc的用戶 #cas.authn.accept.users=casuser::Mellon cas.authn.jdbc.query[0].sql=select * from cms_auth_user where user_name=? cas.authn.jdbc.query[0].healthQuery= cas.authn.jdbc.query[0].isolateInternalQueries=false cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/castest?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false cas.authn.jdbc.query[0].failFast=true cas.authn.jdbc.query[0].isolationLevelName=ISOLATION_READ_COMMITTED cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].leakThreshold=10 cas.authn.jdbc.query[0].propagationBehaviorName=PROPAGATION_REQUIRED cas.authn.jdbc.query[0].batchSize=1 cas.authn.jdbc.query[0].user=root cas.authn.jdbc.query[0].password=123456 #cas.authn.jdbc.query[0].ddlAuto=create-drop cas.authn.jdbc.query[0].maxAgeDays=180 cas.authn.jdbc.query[0].autocommit=false cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver cas.authn.jdbc.query[0].idleTimeout=5000
# cas.authn.jdbc.query[0].credentialCriteria=
# cas.authn.jdbc.query[0].name=
# cas.authn.jdbc.query[0].order=0
# cas.authn.jdbc.query[0].dataSourceName=
# cas.authn.jdbc.query[0].dataSourceProxy=false

cas.authn.jdbc.query[0].fieldPassword=password

# cas.authn.jdbc.query[0].fieldExpired=
# cas.authn.jdbc.query[0].fieldDisabled=
# cas.authn.jdbc.query[0].principalAttributeList=sn,cn:commonName,givenName

#passwordEncoder.type可以自定義加密方式
#cas.authn.jdbc.query[0].passwordEncoder.type=DEFAULT 
#多屬性 #CAS默認返回給客戶端的只有用戶ID,如果想返回更多的內容就要加上這段內容了,上面這個配置會返回cms_auth_user表下的所有字段。 #如何獲取這些字段可以在客戶端通過以下代碼: #AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal(); #final Map attributes = principal.getAttributes(); cas.authn.attributeRepository.jdbc[0].singleRow=true cas.authn.attributeRepository.jdbc[0].order=0 cas.authn.attributeRepository.jdbc[0].url=jdbc:mysql://127.0.0.1:3306/castest?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false cas.authn.attributeRepository.jdbc[0].username=user_name cas.authn.attributeRepository.jdbc[0].user=root cas.authn.attributeRepository.jdbc[0].password=123456 cas.authn.attributeRepository.jdbc[0].sql=select * from cms_auth_user where {0} cas.authn.attributeRepository.jdbc[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.attributeRepository.jdbc[0].ddlAuto=none cas.authn.attributeRepository.jdbc[0].driverClass=com.mysql.jdbc.Driver cas.authn.attributeRepository.jdbc[0].leakThreshold=10 cas.authn.attributeRepository.jdbc[0].propagationBehaviorName=PROPAGATION_REQUIRED cas.authn.attributeRepository.jdbc[0].batchSize=1 cas.authn.attributeRepository.jdbc[0].healthQuery=SELECT 1 cas.authn.attributeRepository.jdbc[0].failFast=true

2、修改pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.apereo.cas</groupId>
    <artifactId>cas-overlay</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>

    <build>
        <plugins>
            <!--注釋掉無用組件 <plugin>
                <groupId>com.rimerosolutions.maven.plugins</groupId>
                <artifactId>wrapper-maven-plugin</artifactId>
                <version>0.0.4</version>
                <configuration>
                    <verifyDownload>true</verifyDownload>
                    <checksumAlgorithm>MD5</checksumAlgorithm>
                </configuration>
            </plugin>
            -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${springboot.version}</version>
                <configuration>
                    <mainClass>${mainClassName}</mainClass>
                    <addResources>true</addResources>
                    <executable>${isExecutable}</executable>
                    <layout>WAR</layout>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <warName>cas</warName>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <recompressZippedFiles>false</recompressZippedFiles>
                    <archive>
                        <compress>false</compress>
                        <manifestFile>${manifestFileToUse}</manifestFile>
                    </archive>
                    <overlays>
                        <overlay>
                            <groupId>org.apereo.cas</groupId>
                            <artifactId>cas-server-webapp${app.server}</artifactId>
                            <excludes>
                                <exclude>WEB-INF/classes/application.properties</exclude>
                                <!--<exclude>WEB-INF/classes/bootstrap.properties</exclude>-->
                                <!--<exclude>WEB-INF/classes/log4j2.xml</exclude>-->
                                <!--若要使resources修改的配置文件生效 在這里添加被覆蓋的配置文件
                                帶上配置文件在overlay中路徑-->
                            </excludes>
                        </overlay>
                    </overlays>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
            </plugin>
        </plugins>
        <finalName>cas</finalName>
    </build>

    <properties>
        <cas.version>5.2.6</cas.version>
        <springboot.version>1.5.12.RELEASE</springboot.version>
        <!-- app.server could be -jetty, -undertow, -tomcat, or blank if you plan to provide appserver -->
        <app.server>-tomcat</app.server>

        <mainClassName>org.springframework.boot.loader.WarLauncher</mainClassName>
        <isExecutable>false</isExecutable>
        <manifestFileToUse>
            ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF
        </manifestFileToUse>

        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <!-- 注釋掉  在settings.xml配置阿里雲鏡像  速度會很快  用下面的地址會很慢
    <repositories>
        <repository>
            <id>sonatype-releases</id>
            <url>http://oss.sonatype.org/content/repositories/releases/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
        <repository>
            <id>sonatype-snapshots</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
        <repository>
            <id>shibboleth-releases</id>
            <url>https://build.shibboleth.net/nexus/content/repositories/releases</url>
        </repository>
    </repositories>
    -->


    <profiles>
        <profile>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <id>default</id>
            <dependencies>
                <dependency>
                    <groupId>org.apereo.cas</groupId>
                    <artifactId>cas-server-webapp${app.server}</artifactId>
                    <version>${cas.version}</version>
                    <type>war</type>
                    <scope>runtime</scope>
                </dependency>
                <!--STEP2 引入數據庫認證相關 start-->
                <dependency>
                    <groupId>org.apereo.cas</groupId>
                    <artifactId>cas-server-support-jdbc</artifactId>
                    <version>${cas.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apereo.cas</groupId>
                    <artifactId>cas-server-support-jdbc-drivers</artifactId>
                    <version>${cas.version}</version>
                    <scope>runtime</scope>
                </dependency>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.38</version>
                </dependency>
                <!--數據庫認證相關 end-->
            </dependencies>
        </profile>
        <!--注釋掉無用組件
        <profile>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <id>exec</id>
            <properties>
                <mainClassName>org.apereo.cas.web.CasWebApplication</mainClassName>
                <isExecutable>true</isExecutable>
                <manifestFileToUse></manifestFileToUse>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.soebes.maven.plugins</groupId>
                        <artifactId>echo-maven-plugin</artifactId>
                        <version>0.3.0</version>
                        <executions>
                            <execution>
                                <phase>prepare-package</phase>
                                <goals>
                                    <goal>echo</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <echos>
                                <echo>Executable profile to make the generated CAS web application executable.</echo>
                            </echos>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        -->
        <profile>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <id>bootiful</id>
            <properties>
                <app.server>-tomcat</app.server>
                <isExecutable>false</isExecutable>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.apereo.cas</groupId>
                    <artifactId>cas-server-webapp${app.server}</artifactId>
                    <version>${cas.version}</version>
                    <type>war</type>
                    <scope>runtime</scope>
                </dependency>
            </dependencies>
        </profile>

        <!--注釋掉無用組件
        <profile>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <id>pgp</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.s4u.plugins</groupId>
                        <artifactId>pgpverify-maven-plugin</artifactId>
                        <version>1.1.0</version>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>check</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <pgpKeyServer>hkp://pool.sks-keyservers.net</pgpKeyServer>
                            <pgpKeysCachePath>${settings.localRepository}/pgpkeys-cache</pgpKeysCachePath>
                            <scope>test</scope>
                            <verifyPomFiles>true</verifyPomFiles>
                            <failNoSignature>false</failNoSignature>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        -->
    </profiles>
</project>

3、重新打包部署  然后登錄認證

(1)打開新的登錄頁面不再提示:不安全連接和固定用戶警告

(2)使用原先默認的casuser登錄提示:認證信息無效

(3)使用數據庫表里配置的用戶和密碼登錄

(4)注銷用戶

 

參考:
CAS 5.1.x 的搭建和使用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM