本文主要講解的是jhipster與cas的整合,目前這一方面國内的資料少之甚少,筆者在踩過無數次坑,填無數次坑後決定将這一方面的技術記錄下來,分享給大家。閱讀本文,同時有過jhipster和cas使用經驗的人了解起來比較容易,您可以略過介紹jhipster和cas配置的部分,直接看jhipster與cas的整合部分。
廢話不多說,讓我們進入主題。
jhipster是一個開發平台,用于開發和部署基于spring-boot啟動的angularjs web應用程式,通俗的講,他最大的特點就是應用程式的所有前端+後端代碼都是自動生成的,并且所用資料庫、架構、技術棧可以根據需要在生成時随意選擇。
jhipster所需環境:
1.jdk8
2. Maven 或 Gradle
3.Git
4.Node.js
jhipster安裝步驟:
1.安裝npm : npm install -g npm
2.安裝Yeoman : npm install -g yo
3.安裝bower(适用于生成angularjs 1 應用):npm install -g bower
4.安裝Gulp(适用于生成angularjs 1 應用) :npm install -g gulp-cli
5.安裝jhipster :npm install -g generator-jhipster
6.(可選項)安裝yarn: npm install -g yarn
以上内容來自jhipster官網,如需更詳細,請仔細閱讀官網内容:http://www.jhipster.tech/installation/
jhipster環境安裝完畢,接下來我們生成一個jhipster項目
1.打開任意一個檔案夾,shift+滑鼠右鍵打開控制台輸入 yo jhipster 如圖所示:
接下來的問題回答,依次如圖所示:
問題4為選擇使用者認證技術,問題11為選擇開源技術,問題12為選擇前端架構
如需詳細解釋請參考官網:http://www.jhipster.tech/creating-an-app/
回答完問題之後npm會自動下載下傳jhipster所需的元件 (有些元件如果下載下傳不下來,請使用你(翻)懂(薔)得)
接下來我們需要修改jhipster的資料源,打開jhipster項目 src\main\resources\config下的application-dev.yml檔案,修改資料源如下文所示(mysql資料庫):
spring:
profiles:
active: dev
include: swagger
devtools:
restart:
enabled: true
livereload:
enabled: false # we use gulp + BrowserSync for livereload
jackson:
serialization.indent_output: true
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/kettle?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root
修改完資料源後,在項目根目錄打開控制台依次運作bower install ,gulp install 待成功之後運作mvn spring-boot:run或點選根目錄的mvnn.cmd檔案啟動jhipster,啟動成功入下圖所示:
在浏覽器運作localhost:(端口号) ,成功如下圖所示:
好了,關于jhipster的配置與安裝就介紹到這裡,jhipster生成實體部分不在這裡講解,詳細請參考官網文檔http://www.jhipster.tech/creating-an-entity/
接下來講解CAS服務端的搭建與部署,網上這方面的文章有很多,方法不統一,我的方法僅供大家參考。
大緻總結一下本地配置CAS服務端的幾個步驟,如下:
1.在hosts中配置域名
2. 用jdk中的 java tool生成cas所需秘鑰
3.下載下傳cas服務端jar包
4.配置cas服務端tomcat的server.xml
1.打開本地hosts配置3個可用域名
127.0.0.1 demo.kettle.com (cas服務端域名)
127.0.0.1 app1.kettle.com (cas用戶端域名)
127.0.0.1 app2.kettle.com (cas用戶端域名)
2. 用jdk中的 java tool生成cas所需秘鑰
建立證書(這裡的keypassword與keystorepassword都為kettle):
使用java keytool證書工具 :找到系統jdk所在的位置,進入bin目錄運作,打開指令行運作:
keytool -genkey -alias kettle -keyalg RSA -keysize 1024 -keypass kettle -validity 365 -keystore F:\keys\kettle\kettle.keystore -storepass kettle
導出證書:
keytool -export -alias kettle -keystore F:\keys\kettle\kettle.keystore -file F:\keys\kettle.crt -storepass kettle
把證書導入到用戶端JDK中(win7要使用 ctrl+shift+enter打開cmd擷取系統管理者權限):
keytool -import -keystore "%JAVA_HOME%\jre\lib\security\cacerts" -file F:\keys\kettle.crt -alias kettle
密碼輸入:changeit
3.下載下傳cas服務端jar包:
下載下傳 cas-server-web-4.0.0.zip 解壓後 到modules檔案夾中找到cas-management-webapp-4.0.0.war
将cas-server-webapp-4.0.0.war改名為cas.war拷貝到tomcat目錄的webapps檔案夾中
修改tomcat檔案夾下的conf/server.xml檔案,使其支援https:
4.配置cas服務端tomcat的server.xml
修改8080端口的内容使其指向8443:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
去掉下面8443端口的注釋,加入證書資訊
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="F:\keys\kettle\kettle.keystore"
keystorePass="kettle"
truststoreFile="C:\Program Files\Java\jdk8\jre\lib\security\cacerts"
/>
去tomcat目錄下的bin檔案夾點選startup.bat啟動tomcat,浏覽器輸入https://demo.kettle.com:8443/cas 點選繼續前往
進入cas認證中心 如下圖所示:
初始使用者名為casuser密碼Mellon 登入成功如下圖所示,表示配置成功, 如果啟動失敗 請檢查證書是否生成正确
目前為止,jhipster的配置與cas的配置已經講解完畢,下面我們着手解決jhipster與cas的內建問題,由于修改的檔案比較多,檢視源碼請到如下位址下載下傳:https://pan.baidu.com/s/1hrSa3ZI jhipster.src.main.rar
1.修改核心配置檔案SecurityConfiguration.java ,位置如下:
2.在config目錄加入CasProperties和JhipsterProperties并替換掉原來io.github.jhipster包中的casProperties和jhipsterProperties,替換後的config目錄如下:
3.在web目錄下加入SimpleController檔案,作為cas登入的入口
4.在security下加入cas檔案夾,加入如下檔案:
CustomSessionFixationProtectionStrategy
CustomSingleSignOutFilter
CustomSingleSignOutHandler
RememberCasAuthenticationEntryPoint
RememberCasAuthenticationProvider
RememberWebAuthenticationDetails
RememberWebAuthenticationDetailsSource
同時修改security檔案夾下的:
AjaxAuthenticationFailureHandler
AjaxAuthenticationSuccessHandler
AjaxLogoutSuccessHandler
修改security檔案夾下的DomainUserDetailsService檔案名為UserDetailsService同時修改其中的内容:
DomainUserDetailsService
修改後的目錄結構如下圖所示:
5.修改service/dto檔案夾下的UserDTO
6.修改webapp/app/components/login下的 login.controller.js和login.service.js使之适應cas
7.修改webapp/app/service/auth的 auth.service.js和auth.session.service.js使之适應cas
8.修改src/main/resources/config下的application-dev.yml,設定jhipster的SSL
代碼如下:
# ===================================================================
# Spring Boot configuration for the "dev" profile.
#
# This configuration overrides the application.yml file.
#
# More information on profiles: https://jhipster.github.io/profiles/
# More information on configuration properties: https://jhipster.github.io/common-application-properties/
# ===================================================================
# ===================================================================
# Standard Spring Boot properties.
# Full reference is available at:
# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# ===================================================================
spring:
profiles:
active: dev
include: swagger
devtools:
restart:
enabled: true
livereload:
enabled: false # we use gulp + BrowserSync for livereload
jackson:
serialization.indent_output: true
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/kettle?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root
h2:
console:
enabled: false
jpa:
database-platform: io.github.jhipster.domain.util.FixedH2Dialect
database: H2
show-sql: true
properties:
hibernate.id.new_generator_mappings: true
hibernate.cache.use_second_level_cache: true
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true
hibernate.cache.region.factory_class: io.github.jhipster.config.jcache.NoDefaultJCacheRegionFactory
data:
elasticsearch:
cluster-name:
cluster-nodes:
properties:
path:
logs: target/elasticsearch/log
data: target/elasticsearch/data
mail:
host: localhost
port: 25
username:
password:
messages:
cache-seconds: 1
thymeleaf:
cache: false
liquibase:
contexts: dev
# ===================================================================
# To enable SSL, generate a certificate using:
# keytool -genkey -alias ausp -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
#
# You can also use Let's Encrypt:
# https://maximilian-boehm.com/hp2121/Create-a-Java-Keystore-JKS-from-Let-s-Encrypt-Certificates.htm
#
# Then, modify the server.ssl properties so your "server" configuration looks like:
#
# server:
# port: 8443
# ssl:
# key-store: keystore.p12
# key-store-password: <your-password>
# keyStoreType: PKCS12
# keyAlias: ausp
# ===================================================================
server:
port: 18080
address: app1.kettle.com
ssl:
key-store: F:/keys/kettle/kettle.keystore
key-alias: kettle
key-password: kettle
key-store-password: kettle
enabled: true
# ===================================================================
# JHipster specific properties
#
# Full reference is available at: https://jhipster.github.io/common-application-properties/
# ===================================================================
jhipster:
http:
version: V_1_1 # To use HTTP/2 you will need SSL support (see above the "server.ssl" configuration)
cache: # Cache configuration
ehcache: # Ehcache configuration
time-to-live-seconds: 3600 # By default objects stay 1 hour in the cache
max-entries: 100 # Number of objects in each cache entry
# CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
cors:
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
security:
remember-me:
# security key (this key should be unique for your application, and kept secret)
key: f8df3decb4f433f9d3b0491343f26812619667b7
mail: # specific JHipster mail property, for standard properties see MailProperties
from: [email protected]
base-url: http://127.0.0.1:8080
metrics: # DropWizard Metrics configuration, used by MetricsConfiguration
jmx.enabled: true
graphite: # Use the "graphite" Maven profile to have the Graphite dependencies
enabled: false
host: localhost
port: 2003
prefix: ausp
prometheus: # Use the "prometheus" Maven profile to have the Prometheus dependencies
enabled: false
endpoint: /prometheusMetrics
logs: # Reports Dropwizard metrics in the logs
enabled: false
report-frequency: 60 # in seconds
logging:
logstash: # Forward logs to logstash over a socket, used by LoggingConfiguration
enabled: false
host: localhost
port: 5000
queue-size: 512
# ===================================================================
# Application specific properties
# Add your own application properties here, see the ApplicationProperties class
# to have type-safe configuration, like in the JHipsterProperties above
#
# More documentation is available at:
# https://jhipster.github.io/common-application-properties/
# ===================================================================
application:
# ===================================================================
# CAS Integration
# ===================================================================
cas:
service:
security: https://app1.kettle.com:18080/login/cas
home: https://app1.kettle.com:18080/
url:
prefix: https://demo.kettle.com:8443/cas/
login: https://demo.kettle.com:8443/cas/login
logout: https://demo.kettle.com:8443/cas/logout
最後到cas服務端(最開始配置tomcat承載的那個)找到webapps/cas/WEB-INF/ 下的deployerConfigContext.xml并修改,使之連接配接jhipster資料庫
注釋掉primaryAuthenticationHandler,并加入dbAuthHandler,代碼如下:
注:這裡屏蔽了密碼加密方式,測試時請在資料中手動加入一個明文賬号進行測試!
<constructor-arg>
<map>
<!--
| IMPORTANT
| Every handler requires a unique name.
| If more than one instance of the same handler class is configured, you must explicitly
| set its name to something other than its default name (typically the simple class name).
-->
<entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" />
<entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>
<!-- <entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" /> -->
</map>
</constructor-arg>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
p:driverClass="com.mysql.jdbc.Driver" p:jdbcUrl="jdbc:mysql://localhost:3306/kettle?useUnicode=true&characterEncoding=utf8&noAccessToProcedureBodies=true&autoReconnect=true&zeroDateTimeBehavior=convertToNull"
p:user="root"
p:password="root" />
<!-- 密碼加密方式-->
<!-- <bean id="passwordEncoder" -->
<!-- class="com.my.cas.authentication.handler.SelfPasswordEncoder" -->
<!-- c:encodingAlgorithm="SHA1" -->
<!-- p:characterEncoding="UTF-8" /> -->
<!-- <bean id="dbAuthHandler" -->
<!-- class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler" -->
<!-- p:dataSource-ref="dataSource" -->
<!-- p:sql="select password_hash from jhi_user where login=? " -->
<!-- p:passwordEncoder-ref="passwordEncoder" -->
<!-- /> -->
<bean id="dbAuthHandler"
class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler"
p:dataSource-ref="dataSource"
p:sql="select password_hash from jhi_user where login=? "
/>