CAS客户端使用SpringSecurity访问CAS发布的属性

摘要

  • CAS服务端基于cas-overlay-template-5.3.14,已实现基于jdbc的自定义登录策略、验证码、动态service配置、多属性返回,等等
  • CAS客户端基于spring-boot-2.3.3.RELEASE,spring-security-cas-5.3.4.RELEASE
  • 本文代码地址:https://github.com/hanqunfeng/springbootchapter/tree/master/chapter36
  • 其重点是client的UserDetailsService的实现类要继承自AbstractCasAssertionUserDetailsService

cas服务配置

  • 如果是json配置方式:services目录下需要为每个客户端配置一个json文件,如client1-10000005.json
{
  "@class" : "org.apereo.cas.services.RegexRegisteredService",
  "serviceId" : "^(https|http|imaps)://localhost:8081.*", #对应客户端的地址匹配路径
  "name" : "client1",  #与文件名称对应
  "id" : 10000005,     #与文件名称对应
  "description" : "This service definition authorizes all application urls that support HTTPS and IMAPS protocols.",
  "evaluationOrder" : 10, #顺序id不能重复
  "logoutType" : "BACK_CHANNEL", #固定写法
  "logoutUrl" : "http://localhost:8081/",  #客户端地址,用于单点登出时通知客户端使用
  "attributeReleasePolicy": { # 属性返回策略
    "@class": "org.apereo.cas.services.ReturnAllAttributeReleasePolicy"
  },
  "accessStrategy" : { #是否允许该客户端访问单点登录,肯定是要开启的啊
    "@class" : "org.apereo.cas.services.DefaultRegisteredServiceAccessStrategy",
    "enabled" : true,
    "ssoEnabled" : true
  }
}

cas多属性返回

  • services的json文件中要增加如下配置
# 返回全部配置属性
"attributeReleasePolicy": {
    "@class": "org.apereo.cas.services.ReturnAllAttributeReleasePolicy"
  }

# 返回指定配置属性,这里指定只返回username和email两个属性
  "attributeReleasePolicy" : {
    "@class" : "org.apereo.cas.services.ReturnAllowedAttributeReleasePolicy",
    "allowedAttributes" : [ "java.util.ArrayList", [ "username", "email" ] ]
  }

动态service

如果使用代码的方式维护service,则也要根据情况来创建返回策略,
参考代码chapter36/cas-overlay-template-5.3.14/src/main/java/com/cas/controller/ServiceController.java
  • 配置属性
# 动态services配置
################################################
# 开启识别Json文件,默认false
# 这一段表示从json文件里面初始化服务,如果我们配置了这个,就会将这写json里面的数据,都会自动导入到数据库中
cas.serviceRegistry.initFromJson=true
cas.serviceRegistry.watcherEnabled=true
#设置配置的服务,一直都有,不会给清除掉 , 第一次使用,需要配置为 create-drop
#create-drop 重启cas服务的时候,就会给干掉
#create  没有表就创建,有就不创建
#none 什么也不做
#update 更新
#Unrecognized legacy `hibernate.hbm2ddl.auto` value : create-drops
cas.serviceRegistry.jpa.ddlAuto=update
#配置将service配置到数据库中
cas.serviceRegistry.jpa.isolateInternalQueries=false
cas.serviceRegistry.jpa.url=${jdbc.url}
cas.serviceRegistry.jpa.user=${jdbc.username}
cas.serviceRegistry.jpa.password=${jdbc.password}
#这个必须是org.hibernate.dialect.MySQL5Dialect ,我就是这个问题导致表创建失败
cas.serviceRegistry.jpa.dialect=org.hibernate.dialect.MySQL5Dialect
cas.serviceRegistry.jpa.driverClass=${jdbc.driver}
cas.serviceRegistry.jpa.leakThreshold=10
cas.serviceRegistry.jpa.batchSize=1
cas.serviceRegistry.jpa.autocommit=true
cas.serviceRegistry.jpa.idleTimeout=5000
#配置结束
################################################
  • 这里说一下delete异常的问题,可以引入jdbcTemplate直接操作数据表,参考chapter36/cas-overlay-template-5.3.14/src/main/java/com/cas/config/DataSourceConfig.java
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from regexregisteredservice where serviceId = '" + serviceId + "'");
if (list != null && list.size() > 0) {
    has_data = true;
    jdbcTemplate.update("delete from regexregisteredservice where serviceId = '" + serviceId + "'");
}

 //执行load生效
 servicesManager.load();

基于配置文件返回属性

#####################################################
## 属性返回
cas.authn.attributeRepository.jdbc[0].sql=select username,password,email from cas_user where username=?

# 格式cas.authn.attributeRepository.jdbc[0].attributes.key=value
# 返回上面查询结果的username,属性key名称也为username ,以下雷同
cas.authn.attributeRepository.jdbc[0].attributes.username=username
cas.authn.attributeRepository.jdbc[0].attributes.password=password
cas.authn.attributeRepository.jdbc[0].attributes.email=email

cas.authn.attributeRepository.jdbc[0].singleRow=true
cas.authn.attributeRepository.jdbc[0].order=0
cas.authn.attributeRepository.jdbc[0].requireAllAttributes=true
# cas.authn.attributeRepository.jdbc[0].caseCanonicalization=NONE|LOWER|UPPER
# cas.authn.attributeRepository.jdbc[0].queryType=OR|AND

cas.authn.attributeRepository.jdbc[0].username=username
#数据库连接
cas.authn.attributeRepository.jdbc[0].url=${jdbc.url}
#数据库dialect配置
cas.authn.attributeRepository.jdbc[0].dialect=${jdbc.dialect}
#数据库用户名
cas.authn.attributeRepository.jdbc[0].user=${jdbc.username}
#数据库用户密码
cas.authn.attributeRepository.jdbc[0].password=${jdbc.password}
#数据库事务自动提交
cas.authn.attributeRepository.jdbc[0].autocommit=true
#数据库驱动
cas.authn.attributeRepository.jdbc[0].driverClass=${jdbc.driver}
#超时配置
cas.authn.attributeRepository.jdbc[0].idleTimeout=5000
cas.authn.attributeRepository.jdbc[0].ddlAuto=none
cas.authn.attributeRepository.jdbc[0].leakThreshold=10
cas.authn.attributeRepository.jdbc[0].batchSize=1
cas.authn.attributeRepository.jdbc[0].dataSourceProxy=false

#####################################################

代码实现返回属性内容

  • 这个需要结合自定义登录策略来实现,代码参考:chapter36/cas-overlay-template-5.3.14/src/main/java/com/cas/security/CustomerHandlerAuthentication.java,注意要关闭配置文件的登录策略,否则会失效
  • 注册自定义登录策略,代码参考:chapter36/cas-overlay-template-5.3.14/src/main/java/com/cas/config/CustomAuthenticationConfig.java
  • 然后将其加入自动配置中,chapter36/cas-overlay-template-5.3.14/src/main/resources/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  org.apereo.cas.config.CasEmbeddedContainerTomcatConfiguration,\
  org.apereo.cas.config.CasEmbeddedContainerTomcatFiltersConfiguration,\
  com.cas.config.MyConfiguration,\ #自定义的其它需要加入spring上下文的bean
  com.cas.config.DataSourceConfig,\ #数据源配置,为了引入JdbcTemplate
  com.cas.config.CustomAuthenticationConfig,\  #自定义登录策略配置
  com.cas.config.CustomerAuthWebflowConfiguration #自定义登录流程配置

cas-client-springsecurity

  • 这里说一下,如果不使用springsecurity,而是直接依赖cas-client,其获取cas返回属性的方式
Principal principal = request.getUserPrincipal();
if(principal instanceof AttributePrincipal){
    //cas传递过来的数据
    Map<String,Object> result =( (AttributePrincipal)principal).getAttributes();
    for(Map.Entry<String, Object> entry :result.entrySet()) {
        String key = entry.getKey();
        Object val = entry.getValue();
        System.out.printf("%s:%s\r\n",key,val);
    }
}
  • 使用springsecurity的配置类代码参考:chapter36/springsecurity-client-demo/src/main/java/com/example/springsecuritydemo/config/WebSecurityConfigByCASByAttrs.java
/**
     * cas 认证 Provider
     */
    @Bean
    public CasAuthenticationProvider casAuthenticationProvider() {
        //创建CAS授权认证器
        CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();

        //设置Cas授权认证器相关配置
        casAuthenticationProvider.setServiceProperties(serviceProperties());
        //设置票据校验器
        casAuthenticationProvider.setTicketValidator(cas30ServiceTicketValidator());
        casAuthenticationProvider.setKey("casAuthenticationProviderKey");


        //setUserDetailsService和setAuthenticationUserDetailsService只能设置一个,其目的都是为了初始化属性authenticationUserDetailsService
        //setUserDetailsService的类型为UserDetailsService
        //setAuthenticationUserDetailsService的类型为AuthenticationUserDetailsService<CasAssertionAuthenticationToken>
        // 如果使用setUserDetailsService,则其会对UserDetailsService进行封装,new UserDetailsByNameServiceWrapper(userDetailsService),
        // 将其转换为AuthenticationUserDetailsService<CasAssertionAuthenticationToken>类型
        //这里使用setAuthenticationUserDetailsService是为了接收cas服务端返回的属性,因为CasAssertionAuthenticationToken会接收到返回的属性
        casAuthenticationProvider.setAuthenticationUserDetailsService(userDetailsServiceImplByAttrs());

        return casAuthenticationProvider;
    }

    @Bean
    public UserDetailsServiceImplByAttrs userDetailsServiceImplByAttrs(){
        UserDetailsServiceImplByAttrs userDetailsServiceImplByAttrs = new UserDetailsServiceImplByAttrs();
        return userDetailsServiceImplByAttrs;
    }

  • UserDetailsServiceImplByAttrs的重点就是要继承AbstractCasAssertionUserDetailsService,而不是实现UserDetailsService
//实际可以接收的属性
Map<String, Object> objectMap = assertion.getPrincipal().getAttributes();
  • 这里说一下AbstractCasAssertionUserDetailsService,它有一个实现类GrantedAuthorityFromAssertionAttributesUserDetailsService
    不过其将返回数据都做为用户的权限了,所以其只是用来从服务器端获取用户权限使用
CasAuthenticationToken principal = (CasAuthenticationToken) request.getUserPrincipal();
UserDetails userDetails = principal.getUserDetails();
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) userDetails.getAuthorities();
authorities.stream().forEach(System.out::println);
  • 如果希望灵活使用cas返回属性,则需要自定义实现类,笔者这里将获取到的属性map存储到自定义的CustomerUser属性中了

  • 代码中使用属性

#获取登录的用户名称
String username = request.getRemoteUser();
#获取cas返回属性
CasAuthenticationToken principal = (CasAuthenticationToken) request.getUserPrincipal();
UserDetails userDetails = principal.getUserDetails();
if(userDetails instanceof CustomerUser){
    Map<String, Object> map = ((CustomerUser) userDetails).getMap();
    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value != null) {
            if (value instanceof List) {
                List list = (List) value;
                Iterator iterator = list.iterator();
                int i = 0;
                while (iterator.hasNext()) {
                    Object object = iterator.next();
                    System.out.println("key:" + key + ",values[" + i + "]:" + object.toString());
                    i++;
                }
            } else {
                System.out.println("key:" + key + ",value:" + value.toString());
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 224,289评论 6 522
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 95,968评论 3 402
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 171,336评论 0 366
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 60,718评论 1 300
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 69,734评论 6 399
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,240评论 1 314
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,631评论 3 428
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 40,599评论 0 279
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 47,139评论 1 324
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,166评论 3 345
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,286评论 1 354
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,917评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,604评论 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,075评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,205评论 1 275
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,814评论 3 381
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,351评论 2 365