CAS單點(diǎn)登錄-動態(tài)添加services(七)

前面我們整合客戶端的時候,需要在cas服務(wù)端注冊,使用的是json文件的方式,直接通過配置文件完成配置,但是也存在一定的不方便性。
假如,我們以域名配置的,比如:http://app1.cas.com 注冊,那么又有新的模塊為 http://app2.cas.com 我們總不能每次修改配置,重啟cas服務(wù)吧榛搔。這很不現(xiàn)實(shí),官網(wǎng)給出了如下的解決方式,將數(shù)據(jù)庫來存儲這些數(shù)據(jù)。

具體參考官網(wǎng)
https://apereo.github.io/cas/5.3.x/installation/Configuration-Properties.html#database-service-registry
https://apereo.github.io/cas/5.3.x/installation/JPA-Service-Management.html
https://apereo.github.io/cas/5.3.x/installation/Configuration-Properties-Common.html#database-settings

pom添加依賴

<dependency>
    <groupId>org.apereo.cas</groupId>
    <artifactId>cas-server-support-jpa-service-registry</artifactId>
    <version>${cas.version}</version>
</dependency>
<dependency>
    <groupId>org.apereo.cas</groupId>
    <artifactId>cas-server-core-services-api</artifactId>
    <version>${cas.version}</version>
</dependency>
<dependency>
    <groupId>org.apereo.cas</groupId>
    <artifactId>cas-server-core-authentication-attributes</artifactId>
    <version>${cas.version}</version>
</dependency>

application.properties添加以下屬性

##
# 動態(tài)service 注冊配置
#
#數(shù)據(jù)庫用戶名
cas.serviceRegistry.jpa.user=root
#數(shù)據(jù)庫密碼
cas.serviceRegistry.jpa.password=123456
#mysql驅(qū)動
cas.serviceRegistry.jpa.driverClass=com.mysql.jdbc.Driver
#數(shù)據(jù)庫連接
cas.serviceRegistry.jpa.url=jdbc:mysql://127.0.0.1:3306/sso?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false
cas.serviceRegistry.jpa.dialect=org.hibernate.dialect.MySQL5Dialect
#連接池配置
cas.serviceRegistry.jpa.pool.suspension=false
cas.serviceRegistry.jpa.pool.minSize=6
cas.serviceRegistry.jpa.pool.maxSize=18
cas.serviceRegistry.jpa.pool.maxWait=2000
cas.serviceRegistry.jpa.pool.timeoutMillis=1000
#默認(rèn)為create-drop煌往,表示每次啟動服務(wù)都會清除你之前注冊的cas服務(wù)祈纯,生產(chǎn)環(huán)境生成表結(jié)構(gòu)后需要修改配置為update
cas.serviceRegistry.jpa.ddlAuto=update

停止服務(wù),將會刪除之前創(chuàng)建的service

為了避免重啟服務(wù),導(dǎo)致之前的services丟失,需要將
cas.serviceRegistry.jpa.ddlAuto=update
每次啟動之后,會在mysql中自動生成以下表格

增加http接口,操作數(shù)據(jù)庫添加或刪除service

package com.thtf.cas.controller;

import org.apereo.cas.services.RegexRegisteredService;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ReturnAllAttributeReleasePolicy;
import org.apereo.cas.services.ServicesManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;

/**
 * ========================
 * Created with IntelliJ IDEA.
 * User:pyy
 * Date:2019/6/27
 * Time:14:56
 * Version: v1.0
 * ========================
 */
@RestController
public class ServiceController {
    private Logger logger = LoggerFactory.getLogger(ServiceController.class);

    @Autowired
    @Qualifier("servicesManager")
    private ServicesManager servicesManager;

    /**
     * 注冊service
     * @param serviceId 域名
     * @param id 順序
     * @return
     */
    @GetMapping("/addClient/{serviceId}/{id}")
    public Object addClient(@PathVariable("serviceId") String serviceId, @PathVariable("id") int id) {
        try {
            String a="^(https|imaps|http)://"+serviceId+".*";
            RegexRegisteredService service = new RegexRegisteredService();
            ReturnAllAttributeReleasePolicy re = new ReturnAllAttributeReleasePolicy();
            service.setServiceId(a);
            service.setId(id);
            service.setAttributeReleasePolicy(re);
            service.setName("login");
            //這個是為了單點(diǎn)登出而作用的
            service.setLogoutUrl(new URL("http://"+serviceId));
            servicesManager.save(service);
            //執(zhí)行l(wèi)oad讓他生效
            servicesManager.load();
            ReturnMessage returnMessage = new ReturnMessage();
            returnMessage.setCode(200);
            returnMessage.setMessage("添加成功");
            return returnMessage;
        } catch (Exception e) {
            logger.error("注冊service異常",e);
            ReturnMessage returnMessage = new ReturnMessage();
            returnMessage.setCode(500);
            returnMessage.setMessage("添加失敗");
            return returnMessage;
        }
    }

    /**
     * 刪除service異常
     * @param serviceId
     * @return
     */
    @GetMapping("/deleteClient/{serviceId}/{id}")
    public Object deleteClient(@PathVariable("serviceId") String serviceId,@PathVariable("id") int id) {
        try {

//            String a="^(https|imaps|http)://"+serviceId+".*";
//            String a="^(https|imaps|http)://"+serviceId+".*";
//            RegexRegisteredService service = new RegexRegisteredService();
//            ReturnAllAttributeReleasePolicy re = new ReturnAllAttributeReleasePolicy();
//            service.setServiceId(a);
//            service.setId(id);
//            service.setAttributeReleasePolicy(re);
//            service.setName("login");
//            //這個是為了單點(diǎn)登出而作用的
//            service.setLogoutUrl(new URL("http://"+serviceId));
            String aa = "http://app2.cas.com:8082";
            RegisteredService service = servicesManager.findServiceBy(aa);
            servicesManager.delete(service);
            //執(zhí)行l(wèi)oad生效
            servicesManager.load();

            ReturnMessage returnMessage = new ReturnMessage();
            returnMessage.setCode(200);
            returnMessage.setMessage("刪除成功");
            return returnMessage;
        } catch (Exception e) {
            logger.error("刪除service異常",e);
            ReturnMessage returnMessage = new ReturnMessage();
            returnMessage.setCode(500);
            returnMessage.setMessage("刪除失敗");
            return returnMessage;
        }
    }

    public class ReturnMessage{

        private Integer code;

        private String message;

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

}

配置集成SwaggerAPI集成

  • 第一種方式:
    引入依賴包即可:
<dependency>
  <groupId>org.apereo.cas</groupId>
  <artifactId>cas-server-documentation-swagger</artifactId>
  <version>${cas.version}</version>
</dependency>

cas已經(jīng)配置好swagger,啟動即可使用

  • 第二種方式:
    手動配置:
    引入依賴:
<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

編寫swagger配置類:

package com.thtf.cas.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration("casSwaggerConfiguration")
@EnableSwagger2
public class CasSwaggerConfiguration {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder()
                        .title("CAS Swagger API Documentation")
                        .license("Apache v2")
                        .licenseUrl("https://github.com/apereo/cas/blob/master/LICENSE")
                        .description("CAS Swagger API Documentation")
                        .version("1.0.0")
                        .build());
    }
}

添加ServiceController類和Swagger配置類到:META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.thtf.cas.config.CustomAuthenticationConfiguration,\
com.thtf.cas.config.CasSwaggerConfiguration,\
com.thtf.cas.controller.ServiceController

注意:如果不添加楣号,這個兩個類不會被系統(tǒng)識別

以下Swagger端點(diǎn)可用于分析和測試API:

描述 網(wǎng)址
Swagger API規(guī)范 http://localhost/cas/v2/api-docs
Swagger UI http://localhost/cas/swagger-ui.html

啟動

訪問:http://localhost:8443/cas/swagger-ui.html

測試

  • 此時我們就可以通過接口完成service的添加最易,刪除等操作


  • 查看數(shù)據(jù)庫表


總結(jié)

此中方式可以更加方便管理service,而不用每次有新的應(yīng)用接入時重啟cas-server服務(wù)器炫狱。
而且后面我們可以通過操作regexregisterdservice表 完成對service的管理

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末藻懒,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子视译,更是在濱河造成了極大的恐慌嬉荆,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酷含,死亡現(xiàn)場離奇詭異鄙早,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)第美,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進(jìn)店門蝶锋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人什往,你說我怎么就攤上這事扳缕。” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵躯舔,是天一觀的道長驴剔。 經(jīng)常有香客問我,道長粥庄,這世上最難降的妖魔是什么丧失? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮惜互,結(jié)果婚禮上布讹,老公的妹妹穿的比我還像新娘。我一直安慰自己训堆,他們只是感情好描验,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著坑鱼,像睡著了一般膘流。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上鲁沥,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天呼股,我揣著相機(jī)與錄音,去河邊找鬼画恰。 笑死彭谁,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的阐枣。 我是一名探鬼主播马靠,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼蔼两!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起逞度,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤额划,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后档泽,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體俊戳,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年馆匿,在試婚紗的時候發(fā)現(xiàn)自己被綠了抑胎。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡渐北,死狀恐怖阿逃,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤恃锉,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布搀菩,位于F島的核電站,受9級特大地震影響破托,放射性物質(zhì)發(fā)生泄漏肪跋。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一土砂、第九天 我趴在偏房一處隱蔽的房頂上張望州既。 院中可真熱鬧,春花似錦萝映、人聲如沸吴叶。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽晤郑。三九已至,卻和暖如春贸宏,著一層夾襖步出監(jiān)牢的瞬間造寝,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工吭练, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留诫龙,地道東北人。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓鲫咽,卻偏偏與公主長得像签赃,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子分尸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容