基于SpringbootShiro实现的CAS单点登录

概述

单点登录(Single Sign On,SSO)是一种登录管理机制,主要用于多系统集成,即在多个系统中,用户只需要到一个中央服务器登录一次即可访问这些系统中的任何一个,无须多次登录。常见的例子就是,当我们在淘宝网上登录了之后,如果再访问天猫网的话是不需要再次登录的。

详细

一、运行效果

image.png

image.png

二、实现过程

①、cas单点登录流程图

CAS是SSO的一种实现方式,CAS系统分为服务端与客户端,服务端提供登录认证的功能,客户端需要跳转到服务端进行登录认证,大体流程如下

image.png

②、cas 服务端搭建

CAS 服务端登录需要使用https,在本地我们可以使用 JDK 自带的 keytool 工具生成数字证书,具体流程和配置如下:

a 修改hosts文件,将要配置的CAS服务端域名映射到本地:

127.0.0.1       www.xiaoti.com

b 生成密钥库文件,这里设置密钥库口令,名字与姓氏处填写单点登录服务器的域名(这里是 www.xiaoti.com),其余项可随便填写。654321,设置密钥口令:654321,两者须相同:

c 查看生成的密钥库,输入密钥库密码654321:keytool -list -keystore localhost.keystored 生成crt证书文件,输入密钥库密码654321:keytool -export -alias localhost -keystore localhost.keystore -file localhost.crte 客户端信任证书,这里需要输入的密码是changeit:keytool -import -keystore "D:\Program Files\Java\jdk1.8.0_66\jre\lib\security\cacerts" -file localhost.crt -alias localhostf tomcat配置,server.xml配置:<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"maxThreads="200"SSLEnabled="true"scheme="https"secure="true"clientAuth="false"sslProtocol="TLS"keystoreFile="D:\dev\localhost.keystore"keystorePass="654321" />

 

③、 新建cas服务端项目

CAS已经提供了服务端的基本war包实现,我们只需在其基础上作修改即可,使用maven 的oerlay配置可以通过覆盖的方式来进行修改。

a 新建Maven webapp项目,这里命名为cas-server-demo,引入依赖:

<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/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>gdou.laixiaoming</groupId><artifactId>cas-server-demo</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>cas-server-demo Maven Webapp</name><url>http://maven.apache.org</url><properties><cas.version>5.2.5</cas.version></properties><dependencies><dependency><groupId>org.apereo.cas</groupId><artifactId>cas-server-webapp</artifactId><version>${cas.version}</version><type>war</type><scope>runtime</scope></dependency></dependencies><build><finalName>cas</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><configuration><failOnMissingWebXml>false</failOnMissingWebXml><warName>cas</warName><overlays><overlay><groupId>org.apereo.cas</groupId><artifactId>cas-server-webapp</artifactId></overlay></overlays></configuration></plugin></plugins></build></project>

b 打包,选择上面我们配置的tomcat,启动:
浏览器打开https://www.xiaoti.com:8443/cas/login,默认登录名和密码是casuserMellon,输入后可成功登录

④、配置数据库认证

上面我们成功搭建了CAS Server,但是只能使用默认的用户名和密码进行登录,如果我们的用户名和密码是存储在数据库的话,需要引入 JDBC的支持并进行配置:

a 首先,pom.xml配置文件中增加依赖:

<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></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.36</version></dependency>

b 创建用户密码表:

CREATE TABLE `user` (

  `id` bigint(20) NOT NULL AUTO_INCREMENT,

  `userName` varchar(15) DEFAULT NULL,

  `password` char(32) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

c 将war包中的的application.properties复制出来:

image.png

放到项目如下位置,这里的路径需要对应(确保部署后的application.properties可以对原文件进行覆盖),才能实现更新:

image.png

d 修改application.properties,关于JDBC这里的更详细的配置,可以访问官网 database-authentication部分:

#数据库连接配置

cas.authn.jdbc.query[0].user=root

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

cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver

cas.authn.jdbc.query[0].url=jdbc:mysql://localhost:3306/cas_auth

cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect

##从数据库中获取用户名和密码进行匹配登录

cas.authn.jdbc.query[0].sql=SELECT * FROM `user` WHERE userName=?

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

e 重新构建项目并启动,输入数据库中存在的用户名和密码,是可以成功登录的;

⑤、cas服务端搭建(整合Shiro和SpringBoot)

新建maven项目,引入相关依赖

<?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><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.3.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>gdou.laixiaoming</groupId><artifactId>cas-client-a</artifactId><version>0.0.1-SNAPSHOT</version><name>cas-client-a</name><description>CAS Client Demo.</description><properties><java.version>1.8</java.version><shiro.version>1.4.0</shiro.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- shiro --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>${shiro.version}</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>${shiro.version}</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-cas</artifactId><version>${shiro.version}</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-aspectj</artifactId><version>${shiro.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

shiro配置

扩展CasRealm,在登录成功后,可以获取到登录的用户名,在客户端这边再把用户拥有的角色和权限查询出来并保存:
public class MyCasRealm extends CasRealm{@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//获取用户名String username = (String)principals.getPrimaryPrincipal();SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        authorizationInfo.setRoles(new HashSet<>(Arrays.asList("admin")));
//        authorizationInfo.setStringPermissions(new HashSet<>(Arrays.asList("admin")));return authorizationInfo;}
}Shiro配置:
@Configuration
public class ShiroConfig {@Beanpublic ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();shiroFilterFactoryBean.setSecurityManager(securityManager);//配置自定义casFilterMap<String, Filter> filters = new LinkedHashMap<>();CasFilter casFilter = new CasFilter();casFilter.setFailureUrl("/casFailure");filters.put("cas", casFilter);shiroFilterFactoryBean.setFilters(filters);//配置filter调用链Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();//anon为匿名,不拦截filterChainDefinitionMap.put("/static/**", "anon");filterChainDefinitionMap.put("/casFailure", "anon");//拦截CAS Server返回的ticketfilterChainDefinitionMap.put("/cas", "cas");//退出登录filterChainDefinitionMap.put("/logout", "anon");filterChainDefinitionMap.put("/logouttips", "anon");//需要登录访问的页面filterChainDefinitionMap.put("/**", "user");shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);//service指定了登录成功后的回调地址,回调/cas将被CasFilter拦截,获取服务端返回的Service Ticket进行登录shiroFilterFactoryBean.setLoginUrl("https://www.xiaoti.com:8443/cas/login?service=http://www.localhost1.com:9090/cas");//登录成功后要跳转的链接shiroFilterFactoryBean.setSuccessUrl("/");//未授权跳转页面shiroFilterFactoryBean.setUnauthorizedUrl("/403");return shiroFilterFactoryBean;}@Beanpublic MyCasRealm casRealm(){//使用自定义RealmMyCasRealm casRealm = new MyCasRealm();casRealm.setCachingEnabled(true);casRealm.setAuthenticationCachingEnabled(true);casRealm.setAuthenticationCacheName("authenticationCache");casRealm.setAuthorizationCachingEnabled(true);casRealm.setAuthorizationCacheName("authorizationCache");//指定CAS服务端地址casRealm.setCasServerUrlPrefix("https://www.xiaoti.com:8443/cas");//当前应用的CAS服务URL,用于接收和处理CAS服务端的TicketcasRealm.setCasService("http://www.localhost1.com:9090/cas");return casRealm;}@Beanpublic SecurityManager securityManager(){DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();securityManager.setRealm(casRealm());return securityManager;}/*** Shiro生命周期处理器*/@Beanpublic LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {return new LifecycleBeanPostProcessor();}@Bean@DependsOn({"lifecycleBeanPostProcessor"})public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();advisorAutoProxyCreator.setProxyTargetClass(true);return advisorAutoProxyCreator;}/*** 开启Shiro AOP的注解支持(如@RequiresRoles,@RequiresPermissions)*/@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);return authorizationAttributeSourceAdvisor;}}

⑥、cas单点登出配置

退出登录时,将页面重定向到CAS的退出页面,service参数的设置指定了退出登录后的回调地址:

@GetMapping("/logout")public String logout(){SecurityUtils.getSubject().logout();return "redirect:https://www.xiaoti.com:8443/cas/logout?service=https://www.xiaoti.com:9090/logouttips";}

service参数名可以在CAS服务端通过修改application.properties进行配置,关于登出的更多配置,可见官网:

#单点登出

#配置允许登出后跳转到指定页面

cas.logout.followServiceRedirects=true

#跳转到指定页面需要的参数名为 service

cas.logout.redirectParameter=service

在CAS服务端退出后,会向注册的每个服务发送登出请求,该请求可以由SingleSignOutFilter进行拦截并销毁当前会话:

@Configuration
public class CasConfig {@Beanpublic FilterRegistrationBean singleSignOutFilterRegistration() {FilterRegistrationBean registration = new FilterRegistrationBean(new SingleSignOutFilter());registration.addUrlPatterns("/*");return registration;}@Beanpublic ServletListenerRegistrationBean<SingleSignOutHttpSessionListener> singleSignOutListenerRegistration() {ServletListenerRegistrationBean<SingleSignOutHttpSessionListener> registration =new ServletListenerRegistrationBean<>(new SingleSignOutHttpSessionListener());return registration;}
}

⑥、cas单点登出配置

退出登录时,将页面重定向到CAS的退出页面,service参数的设置指定了退出登录后的回调地址:

@GetMapping("/logout")

         public String logout(){

                   SecurityUtils.getSubject().logout();

                   return "redirect:https://www.xiaoti.com:8443/cas/logout?service=https://www.xiaoti.com:9090/logouttips";

         }

#单点登出

#配置允许登出后跳转到指定页面

cas.logout.followServiceRedirects=true

#跳转到指定页面需要的参数名为 service

cas.logout.redirectParameter=service

在CAS服务端退出后,会向注册的每个服务发送登出请求,该请求可以由SingleSignOutFilter进行拦截并销毁当前会话:

@Configuration

public class CasConfig {

  

    @Bean

    public FilterRegistrationBean singleSignOutFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean(new SingleSignOutFilter());

        registration.addUrlPatterns("/*");

        return registration;

    }

  

    @Bean

    public ServletListenerRegistrationBean<SingleSignOutHttpSessionListener> singleSignOutListenerRegistration() {

        ServletListenerRegistrationBean<SingleSignOutHttpSessionListener> registration =

                new ServletListenerRegistrationBean<>(new SingleSignOutHttpSessionListener());

        return registration;

    }

}

⑦、cas服务端配置

客户端搭建好后,需要在CAS服务端上配置哪些服务可以注册到CAS服务端上,服务的管理也有许多方式,这里使用的JSON的方式,需要先在服务端引入相关依赖(更多说明见官网):

<dependency>

                            <groupId>org.apereo.cas</groupId>

                            <artifactId>cas-server-support-json-service-registry</artifactId>

                            <version>${cas.version}</version>

                   </dependency>

然后,在已经生成的war包中找到文件:

image.png

将文件复制到这个位置:

image.png

修改,serviceId指定允许注册的客户端,更多配置见官网:

{

  "@class" : "org.apereo.cas.services.RegexRegisteredService",

  "serviceId" : "^(https|imaps|http)://(www\\.localhost1\\.com:9090|www\\.localhost2\\.com:9091)/.*",

  "name" : "HTTPS and IMAPS",

  "id" : 10000001,

  "description" : "This service definition authorizes all application urls that support HTTPS and IMAPS protocols.",

  "evaluationOrder" : 10000

}

同时在application.properties指定配置文件位置:

#客户端服务注册

cas.serviceRegistry.json.location=classpath:/services

至此,CAS客户端搭建完成了

三、项目结构图

image.png

四、补充

CAS全称为Central Authentication Service即中央认证服务,是一个企业多语言单点登录的解决方案,并努力去成为一个身份验证和授权需求的综合平台。

CAS是由Yale大学发起的一个企业级的、开源的项目,旨在为Web应用系统提供一种可靠的单点登录解决方法(属于 Web SSO )。

CAS协议至少涉及三方:客户端Web浏览器,请求身份验证的Web应用程序和CAS服务器。 它也可能涉及后端服务,如数据库服务器,它没有自己的HTTP接口,但与Web应用程序进行通信。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/80210.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MCU软核 3. Xilinx Artix7上运行cortex-m3软核

0. 环境 - win10 vivado 2018.3 keil mdk - jlink - XC7A35TV12 1. 下载资料 https://keilpack.azureedge.net/pack/Keil.V2M-MPS2_DSx_BSP.1.1.0.pack https://gitee.com/whik/cortex_m3_on_xc7a100t 2. vivado 2018 Create Project -> Next -> -> Project n…

dp(3) - 背包问题(上)

目录 简论 关于dp问题 : ​编辑 0-1背包问题 定义 : 例题 : 题面 : ​编辑 思路 : 代码(二维) : 代码(一维优化版): 完全背包问题 题目链接 : 题面 : ​编辑 思路 : 代码(朴素) : 代码(优化) : 代码(一维优化) : 多重背包问题 题目链接 : 题面 : ​编辑 …

软件测试常用的功能测试方法

功能测试 功能测试就是对产品的各功能进行验证&#xff0c;根据功能测试用例&#xff0c;逐项测试&#xff0c;检查产品是否达到用户要求的功能。针对Web系统的常用测试方法如下&#xff1a; 1. 页面链接检查&#xff1a;每一个链接是否都有对应的页面&#xff0c;并且页面之…

如何判断linux 文件(或lib)是由uclibc还是glibc编译出来的?

工作中使用的编译环境有2套编译器&#xff0c;一个是glibc&#xff0c;一个是uclibc。 有些项目使用的glibc编译的lib&#xff0c;和使用uclibc编译的工程&#xff0c;在一起就会出现reference的编译错误如下&#xff1a; 那和如何来判断一个文件是由哪个编译器编译的呢&#…

软件工程评级B-,有大量调剂名额。北京联合大学考情分析

北京联合大学(B-) 考研难度&#xff08;☆&#xff09; 内容&#xff1a;23考情概况&#xff08;拟录取和复试分析&#xff09;、院校概况、23专业目录、23复试详情、各专业考情分析、各科目考情分析。 正文1239字&#xff0c;预计阅读&#xff1a;3分钟 2023考情概况 北京…

进程,线程,并发相关入门

进程与线程的简单理解 进程是一个独立的执行单元&#xff0c;它拥有自己的内存空间、文件句柄和系统资源.进程是操作系统层面的,每个应用运行就是一个进程.进程之间通常是隔离的&#xff0c;它们不能直接访问对方的内存空间&#xff0c;必须通过进程间通信&#xff08;IPC&…

详细解释HiveSQL执行计划

一、前言 Hive SQL的执行计划描述SQL实际执行的整体轮廓&#xff0c;通过执行计划能了解SQL程序在转换成相应计算引擎的执行逻辑&#xff0c;掌握了执行逻辑也就能更好地把握程序出现的瓶颈点&#xff0c;从而能够实现更有针对性的优化。此外还能帮助开发者识别看似等价的SQL其…

前端面试话术集锦第 12 篇:高频考点(Vue常考基础知识点)

这是记录前端面试的话术集锦第十二篇博文——高频考点(Vue常考基础知识点),我会不断更新该博文。❗❗❗ 这一章节我们将来学习Vue的一些经常考到的基础知识点。 1. 生命周期钩子函数 在beforeCreate钩子函数调用的时候,是获取不到props或者data中的数据的,因为这些数据的…

log4j2漏洞复现

log4j2漏洞复现 漏洞原理 log4j2框架下的lookup查询服务提供了{}字段解析功能&#xff0c;传进去的值会被直接解析。例如${sys:java.version}会被替换为对应的java版本。这样如果不对lookup的出栈进行限制&#xff0c;就有可能让查询指向任何服务&#xff08;可能是攻击者部署…

MC-4/11/01/400 ELAU 软件允许用户完全访问相机设置

MC-4/11/01/400 ELAU 软件允许用户完全访问相机设置 一个完整的Sentinel模具保护解决方案包括一到四台冲击式摄像机、专用红外LED照明和镜头、Sentinel软件以及所有与模压机连接的必要互连组件。摄像机支架基于磁性&#xff0c;可快速、安全、灵活地部署。此外&#xff0c;一个…

部署ik分词器

部署ik分词器 案例版本&#xff1a;elasticsearch-analysis-ik-8.6.2 ​ ES默认自带的分词器对中文处理不够友好&#xff0c;创建倒排索引时可能达不到我们想要的结果&#xff0c;然而IK分词器能够很好的支持中文分词 ​ 因为是集群部署&#xff0c;所以每台服务器中的ES都需…

unity 使用Photon进行网络同步

Pun使用教程 第一步&#xff1a;请确保使用的 Unity 版本等于或高于 2017.4&#xff08;不建议使用测试版&#xff09;创建一个新项目。 第二步&#xff1a;打开资源商店并找到 PUN 2 资源并下载/安装它。 导入所有资源后&#xff0c;让 Unity 重新编译。 第三步&#xf…

Python中Mock和Patch的区别

前言&#xff1a; 嗨喽~大家好呀&#xff0c;这里是魔王呐 ❤ ~! python更多源码/资料/解答/教程等 点击此处跳转文末名片免费获取 在测试并行开发&#xff08;TPD&#xff09;中&#xff0c;代码开发是第一位的。 尽管如此&#xff0c;我们还是要写出开发的测试&#xff0c…

解决SpringMVC在JSP页面取不到ModelAndView中数据

版权声明 本文原创作者&#xff1a;谷哥的小弟作者博客地址&#xff1a;http://blog.csdn.net/lfdfhl 问题描述 ModelAndView携带数据跳转到指定JSP页面后在该页面通过EL表达式取不到原本存放在ModelAndView中的数据。 问题原因 在IDEA中创建Maven工程时web.xml中默认的约束…

医院如何实现安全又稳定的跨网文件数据交换呢?

随着医疗信息化的发展&#xff0c;医院之间需要频繁地进行文件数据交换&#xff0c;以实现诊疗、科研、管理等方面的协同和共享。然而&#xff0c;由于医院网络环境的复杂性和敏感性&#xff0c;跨网文件数据交换面临着安全性和稳定性的双重挑战。如何在保证文件数据不被泄露、…

八、硬改之设备画像

系列文章目录 第一章 安卓aosp源码编译环境搭建 第二章 手机硬件参数介绍和校验算法 第三章 修改安卓aosp代码更改硬件参数 第四章 编译定制rom并刷机实现硬改(一) 第五章 编译定制rom并刷机实现硬改(二) 第六章 不root不magisk不xposed lsposed frida原生修改定位 第七章 安卓…

【leetcode 力扣刷题】栈和队列的基础知识 + 栈的经典应用—匹配

栈和队列的基础知识 栈的经典应用—匹配 栈和队列基础知识232. 用栈实现队列225. 用队列实现栈 20. 有效的括号1047. 删除字符串中的所有相邻重复项 栈和队列基础知识 数据结构课程介绍线性结构的时候&#xff0c;介绍有线性表、链表、栈和队列。线性表&#xff0c;比如array…

【k8s】kube-proxy 工作模式

文章目录 Userspace模式&#xff1a;iptables模式&#xff1a;负载均衡&#xff08;Load Balancing&#xff09; LB轮询&#xff08;Round Robin&#xff09;&#xff1a;SessionAffinity&#xff1a;最少连接&#xff08;Least Connection&#xff09;&#xff1a;IP哈希&…

所有字母异位词

class Solution { public:vector<int> findAnagrams(string s, string p) {std::vector<int> idxs;// 先获取p的hash串std::string dstr getHash(p);for (int i 0; i<s.length(); i) {// 使用滑动窗口&#xff0c;每次截取p的长度串并hashstd::string sub_str…

Acwing 828. 模拟栈

Acwing 828. 模拟栈 题目要求思路讲解代码展示 题目要求 思路讲解 栈&#xff1a;先进后出 队列&#xff1a;先进先出 代码展示 #include <iostream>using namespace std;const int N 100010;int m; int stk[N], tt;int main() {cin >> m;while (m -- ){string o…