cas5.3.1系列之自定义jdbc认证策略

SmileNicky的博客      2022-05-05     279

关键词:

CAS 5.3.1系列之自定义JDBC认证策略(三)

CAS官方文档是介绍基于配置实现jdbc认证的,可以参考我博客:CAS 5.3.1系列之支持JDBC认证登录(二),不过我们也可以通过自定义认证策略的方式实现jdbc认证,pom先加入相关jar

<!-- Custom Authentication -->
        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-core-authentication-api</artifactId>
            <version>${cas.version}</version>
        </dependency>

        <!-- Custom Configuration -->
        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-core-configuration-api</artifactId>
            <version>${cas.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-support-generic</artifactId>
            <version>${cas.version}</version>
        </dependency>

5.3.1版本可以实现AbstractPreAndPostProcessingAuthenticationHandler抽象类,重写doAuthentication方法实现:

package org.muses.jeeplatform.cas.authentication.handler;


import org.apereo.cas.authentication.*;
import org.apereo.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.services.ServicesManager;
import org.muses.jeeplatform.cas.user.model.User;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.security.auth.login.AccountException;
import javax.security.auth.login.FailedLoginException;
import java.security.GeneralSecurityException;
import java.util.*;

public class UsernamePasswordAuthenticationHandler extends AbstractPreAndPostProcessingAuthenticationHandler {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UsernamePasswordAuthenticationHandler.class);

    public UsernamePasswordAuthenticationHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {
        super(name, servicesManager, principalFactory, order);
    }

    @Override
    protected AuthenticationHandlerExecutionResult doAuthentication(Credential credential) throws GeneralSecurityException, PreventedException {
        UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential;

        String username = usernamePasswordCredential.getUsername();
        String password = usernamePasswordCredential.getPassword();


        // 先构建数据库驱动连接池
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://192.169.0.198:33306/jeeplatform");
        dataSource.setUsername("root");
        dataSource.setPassword("root");

        // 创建JDBC模板
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);

        String sql = "SELECT * FROM sys_user WHERE username = ?";

        User info = (User) jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper(User.class));


        if (info == null) {
            throw new AccountException("Sorry, username not found!");
        }

        if (!info.getPassword().equals(password)) {
            throw new FailedLoginException("Sorry, password not correct!");
        } else {

            final List<MessageDescriptor> list = new ArrayList<>();

            return createHandlerResult(usernamePasswordCredential,
                    this.principalFactory.createPrincipal(username, Collections.emptyMap()), list);
        }
    }


    @Override
    public boolean supports(Credential credential) {
        return credential instanceof UsernamePasswordCredential;
    }
}

新增一个配置类,实现AuthenticationEventExecutionPlanConfigurer接口

package org.muses.jeeplatform.cas.authentication.config;


import org.apereo.cas.authentication.*;
import org.apereo.cas.authentication.principal.DefaultPrincipalFactory;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.ServicesManager;
import org.muses.jeeplatform.cas.authentication.handler.UsernamePasswordAuthenticationHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration("UsernamePasswordAuthConfig")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class UsernamePasswordAuthConfig implements AuthenticationEventExecutionPlanConfigurer {

    @Autowired
    private CasConfigurationProperties casProperties;

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


    @Bean
    public PrePostAuthenticationHandler myAuthenticationHandler() {
        return new UsernamePasswordAuthenticationHandler(UsernamePasswordAuthenticationHandler.class.getName(),
                servicesManager, new DefaultPrincipalFactory(), 1);
    }

    @Override
    public void configureAuthenticationExecutionPlan(AuthenticationEventExecutionPlan plan) {
        plan.registerAuthenticationHandler(myAuthenticationHandler());
    }
}

在META-INF文件夹,新增一个命名为spring.factories的文件
在这里插入图片描述

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.muses.jeeplatform.cas.authentication.config.UsernamePasswordAuthConfig

为什么要这样做?因为这样做才能将配置类加载到spring容器,详情需要跟下源码,可以参考我博客:SpringBoot源码学习系列之自动配置原理简介

在这里插入图片描述

在这里插入图片描述

代码例子参考:github下载链接

详情可以参考官方文档:https://apereo.github.io/cas/5.3.x/installation/Configuration-Properties.html

优质参考博客:
https://www.cnblogs.com/jpeanut/tag/CAS/
https://blog.csdn.net/anumbrella/category_7765386.html

cas5.3.1系列之客户端对接(代码片段)

CAS5.3.1系列之客户端对接(五)我们要接入客户端可以常用第三方的库cas-client-autoconfig-support来对接,比较快捷,迅速实现,或者可以用cas-client-support-springboot集成到boot项目pom配置:<!--CAS依赖包--><dependency><groupId>net.... 查看详情

cas5.3.1系列之使用casoverlay搭建服务端(代码片段)

一、CAS服务端搭建1.1CAS支持Http登录配置CAS默认是要https的链接才能登录的,不过学习的话是可以先去掉https限制,本博客介绍的是基于Cas5.3.1的,之前改过4.0,4.2.7的,详情见https://blog.csdn.net/u014427391/category_72662... 查看详情

cas5.3.1系列之使用casoverlay搭建服务端(代码片段)

一、CAS服务端搭建1.1CAS支持Http登录配置CAS默认是要https的链接才能登录的,不过学习的话是可以先去掉https限制,本博客介绍的是基于Cas5.3.1的,之前改过4.0,4.2.7的,详情见https://blog.csdn.net/u014427391/category_7266258.htmlCAS5.3.1是基于S... 查看详情

springcloud系列之自定义gatewayfilterfactory(代码片段)

SpringCloud系列之自定义GatewayFilterFactory学习目的:知道创建一个网关sample知道网关的基本配置知道自定义GatewayFilterFactory类环境准备:JDK1.8SpringBoot2.2.3SpringCloud(Hoxton.SR7)Maven3.2+开发工具IntelliJIDEAsmartGit新增SpringBootInitializer项目:N 查看详情

springboot整合springsecurity之自定义认证(代码片段)

一自定义认证页面1.1说明1.如果用户没有自定义登录页面,springsecurity默认会启动自身内部的登录页面,尽管自动生成的登录页面很方便快速启动和运行,但大多数应用程序都希望定义自己的登录页面。1.2自定义登录... 查看详情

saltstack学习系列之自定义grains

Master端打开存放自定义grains的目录vim/etc/salt/masterfile_roots:base:-/srv/salt/建立自定义模块cd/srv/saltmkdir_grainscd_grains编写自定义grainscatdisk.pyimportosdefdisk():grains={}disk=os.popen(‘fdisk-l|grep‘Disk‘|grep-v‘ 查看详情

springboot系列之自定义枚举类的数据校验注解

SpringBoot系列之自定义枚举类的数据校验注解业务场景:数据校验,需要对枚举类型的数据传参,进行数据校验,不能随便传参。拓展,支持多个参数的枚举数据校验在网上找到很多参考资料,所以本博客基于这些博客进行拓展... 查看详情

flutter之自定义按钮raisedbuttonoutlinebuttoniconbutton等——flutter基础系列(代码片段)

 RaisedButton(凸起的按钮,其实就是Android中的MaterialDesign风格的Button,继承自MaterialButton)RaisedButton的常用属性属性名称值类型属性值onPressedVoidCallback,一般接收一个方法必填参数,按下按钮时触发的回调,接收... 查看详情

springcloud系列之自定义gatewayfilterfactory(代码片段)

SpringCloud系列之自定义GatewayFilterFactory学习目的:知道创建一个网关sample知道网关的基本配置知道自定义GatewayFilterFactory类环境准备:JDK1.8SpringBoot2.2.3SpringCloud(Hoxton.SR7)Maven3.2+开发工具IntelliJIDEAsmartGit新增SpringBootInitializer... 查看详情

微信小程序之自定义模态弹窗(带动画)实例

...工具的快捷键微信小程序的文件结构——微信小程序教程系列(1)微信小程序的生命周期实例演示——微信小程序教程系列(2)微信小程序的动态修改视图层的数据——微信小程序教程系列(3)微信小程序的新建页面——微信... 查看详情

并发编程系列之自定义可以命名的线程池工厂类(代码片段)

在使用多线程时候,有时候需要记录具体是哪些业务执行的,不过按照默认的情况,是会打印pool-1-thread-1这种类型的数据,所以有时候不能确定具体哪些业务线程执行的,可以先写一个线程池sample类,运行... 查看详情

springboot系列之自定义枚举类的数据校验注解(代码片段)

SpringBoot系列之自定义枚举类的数据校验注解业务场景:数据校验,需要对枚举类型的数据传参,进行数据校验,不能随便传参。拓展,支持多个参数的枚举数据校验在网上找到很多参考资料,所以本博客... 查看详情

shiro之自定义realm之继承authorizingrealm(代码片段)

一.Realm基本架构为了快速上手,我们需要知道的是,Shiro将数据库中的数据,存放到Realm这种对象中。而Shiro提供的Realm体系较为复杂,一般我们为了使用Shiro的基本目的就是:认证、授权。所以,一般在真... 查看详情

pytest之自定义mark(代码片段)

在上一篇Pytest系列文章:Pytest之skip、skipif、xfail,主要介绍pytest中skip、skipif、xfail的用法。以下主要介绍pytest自定义配置及用例运行实战。一个完整的项目,测试用例比较多,比如我们想将某些用例用来做冒烟测... 查看详情

agilecontroller认证部分

...增加<AC6605>displayaccounting-schemeacco_scheme1.3设置策略1.3.1定义认证规则1.3.2定义授权结果1.3.3定义授权规则2portal认证操作指导2.1添加设备资源>设备管理>增加2.2添加SSID2.3设置策略2.3.1定义认证规则2.3.2定义授权结果2.3.3定义授... 查看详情

springboot之自定义查询query

  下面讲解下SpringBoot之自定义查询Query的实例SpringBoot之自定义查询Query有HQL语句查询(Hibernate),还可以采用sql语句本地查询BookDao类查询接口1packagecom.hik.dao;23importjava.util.List;45importorg.springframework.data.jpa.repository.J 查看详情

vue之自定义组件

组件(Component)是我的理解就是自定义元素.(一)自定义组件任何一个以.vue结尾的组件内都可以写自定义组件,一个自定义组件的使用主要2个步骤:1.注册:上代码  2.组件使用     查看详情

spring之自定义事件

编写自定义事件的简单流程如下:(1)编写CustomEvent.javapackagecom.tutorialspoint;importorg.springframework.context.ApplicationEvent;publicclassCustomEventextendsApplicationEvent{publicCustomEvent(Objectsource){super(sou 查看详情