博主之前一直使用了cas客户端进行用户的单点登录操作,决定进行源码分析来看cas的整个流程,以便以后出现了问题还不知道是什么原因导致的

cas主要的形式就是通过过滤器的形式来实现的,来,贴上示例配置:

     <listener>
<listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>
</listener> <filter>
<filter-name>SSO Logout Filter</filter-name>
<filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>
</filter> <filter-mapping>
<filter-name>SSO Logout Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- SSO单点登录认证filter -->
<filter>
<filter-name>SSO Authentication Filter</filter-name>
<filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
<init-param>
<!-- SSO服务器地址 -->
<param-name>SSOServerUrl</param-name>
<param-value>http://sso.jxeduyun.com/sso</param-value>
</init-param>
<init-param>
<!-- 统一登录地址 -->
<param-name>SSOLoginUrl</param-name>
<param-value>http://www.jxeduyun.com/App.ResourceCloud/Src/index.php</param-value>
</init-param>
<init-param>
<!-- 应用服务器地址, 域名或者[http://|https://]{ip}:{port} -->
<param-name>serverName</param-name>
<param-value>http://127.0.0.1:9000</param-value>
</init-param>
<init-param>
<!-- 除了openId,是否需要返回loginName以及userId等更多信息 -->
<param-name>needAttribute</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<!-- 可选,不需要单点登录的页面,多个页面以英文逗号分隔,支持正则表达式形式 -->
<!-- 例如:/abc/.*\.jsp,/.*/index\.jsp -->
<param-name>excludedURLs</param-name>
<param-value>/site2\.jsp</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>SSO Authentication Filter</filter-name>
<url-pattern>/TyrzLogin/*</url-pattern>
</filter-mapping> <!-- SSO ticket验证filter -->
<filter>
<filter-name>SSO Ticket Validation Filter</filter-name>
<filter-class>org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>
<init-param>
<!-- 应用服务器地址, 域名或者[http://|https://]{ip}:{port} -->
<param-name>serverName</param-name>
<param-value>http://127.0.0.1:9000</param-value>
</init-param>
<init-param>
<!-- 除了openId,是否需要返回loginName以及userId等更多信息 -->
<param-name>needAttribute</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<!-- SSO服务器地址前缀,用于生成验证地址,和SSOServerUrl保持一致 -->
<param-name>SSOServerUrlPrefix</param-name>
<param-value>http://sso.jxeduyun.com/sso</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>SSO Ticket Validation Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

web.xml

博主用的不是官方的cas的jar包,是第三方要求的又再次封装的jar包,不过就是属性,获取用户信息的逻辑多了点,其他的还是官方的源码,博主懒 的下载官方的jar在进行一步一步的debug看源码了。

基本配置是添加4个过滤器,请求的时候可以进行拦截进行查看,最后一个是jfinal的开发框架,类似spring,不用管,

以上是jetty抓到请求时,进行获取过滤的流程,只关注cas的这四个,里面涉及到了缓存过滤器(节点类型存储)

全部进行路径URL匹配完之后,会获取到需要进行执行的过滤器,SSO Logout Filter->SSO Authentication Filter->SSO Ticket Validation Filter->CAS Assertion Thread Local Filter->jfinal->default

那我们就来一个一个看看,每个过滤器都做了哪些事。

SSO Logout Filter,从名字上看,应该是个退出的流程操作。来源吗附上:

 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
//查看请求中是否带有ticket参数
if (!handler.isTokenRequest(request) && !CommonUtils.isNotBlank(request.getParameter("ticket"))) {
//如果没有的ticket参数,查看是否是退出请求
if (handler.isLogoutRequest(request)) {
if (this.sessionMappingStorage != null && !this.sessionMappingStorage.getClass().equals(HashMapBackedSessionMappingStorage.class)) {
//是退出请求,直接销毁session,直接return,不会在执行其他过滤器
handler.destroySession(request, response);
return;
}
this.log.trace("Ignoring URI " + request.getRequestURI());
} else {
handler.recordSession(request);
}
///继续执行下一个执行器
filterChain.doFilter(servletRequest, servletResponse);
}
AuthenticationFilter,该过滤器主要做法:
 public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
String requestedUrl = ((HttpServletRequest)servletRequest).getServletPath();
boolean isExcludedUrl = false;
//这里会获取到xml中的排除需要过滤的URL配置
if (this.excludedRequestUrlPatterns != null && this.excludedRequestUrlPatterns.length > 0) {
Pattern[] arr$ = this.excludedRequestUrlPatterns;
int len$ = arr$.length; for(int i$ = 0; i$ < len$; ++i$) {
Pattern p = arr$[i$];
if (isExcludedUrl = p.matcher(requestedUrl).matches()) {
break;
}
}
} HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
//如果当前URL是被排除,不需要校验cas单点登录的话,直接跳过当前过滤器,进行下一步
if (this.isIgnoreSSO() && isExcludedUrl) {
filterChain.doFilter(request, response);
} else {
//如果当前不被排除在外,查看白名单URL,也可以直接跳过该过滤器
boolean isWhiteUrl = false;
if (this.whiteRequestUrlPatterns != null && this.whiteRequestUrlPatterns.length > 0) {
Pattern[] arr$ = this.whiteRequestUrlPatterns;
int len$ = arr$.length; for(int i$ = 0; i$ < len$; ++i$) {
Pattern p = arr$[i$];
if (isWhiteUrl = p.matcher(requestedUrl).matches()) {
break;
}
}
} if (isWhiteUrl) {
filterChain.doFilter(request, response);
} else {
//如果都没匹配上,说明该URL是需要进行校验查看的
HttpSession session = request.getSession(false);
//从session中取出改属性值,查看当前session是否已经认证过了。如果认证过了了,可以跳过该过滤器
Assertion assertion = session != null ? (Assertion)session.getAttribute("_const_cas_assertion_") : null;
//第一次请求的时候,改对象一定为null,因为没人登录过
if (assertion != null) {
filterChain.doFilter(request, response);
} else {
String serviceUrl = this.constructServiceUrl(request, response);
String ticket = CommonUtils.safeGetParameter(request, this.getArtifactParameterName());
//查看是否session中有_const_cas_gateway_该属性值,第一次登录也没有
boolean wasGatewayed = this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);
//如果都没有
if (!CommonUtils.isNotBlank(ticket) && !wasGatewayed) {
String encodedService;
//查看是否是cas服务器return回调我们的这个接口请求,该属性值在下面,也就是第一次登录的时候,设置的
if (request.getSession().getAttribute("casreturn") != null) {
request.getSession().removeAttribute("casreturn");
if (isExcludedUrl) {
filterChain.doFilter(request, response);
} else {
encodedService = Base64.encodeBase64String(serviceUrl.getBytes());
encodedService = encodedService.replaceAll("[\\s*\t\n\r]", "");
if (!this.SSOLoginUrl.startsWith("https://") && !this.SSOLoginUrl.startsWith("http://")) {
this.SSOLoginUrl = this.getServerName() + (this.getServerName().endsWith("/") ? "" : "/") + this.SSOLoginUrl;
}
//-------------@这里----------------------
//一直以为是所有校验都没有参数后,在下面才是跳转到登录页,,没想到,直接回调了,并没有让用户去登陆,而是在这里才去调用登录页
//让用户去登陆。大坑
response.sendRedirect(CommonUtils.joinUrl(this.SSOLoginUrl, "nextpage=" + encodedService));
}
} else {
//第一次登录的时候是这里,他会将你xml中的cas服务器地址拼接成login登录地址,我们当前请求的URL编码之后,会被cas登录成功后回调使用
encodedService = this.SSOServerUrl + "/login?service=" + URLEncoder.encode(serviceUrl, "UTF-8") + "&redirect=true";
//并且设置cas服务器回调标识
request.getSession().setAttribute("casreturn", true);
//第一次登录的时候,只能到这里了,因为ticket参数,或则session中_const_cas_assertion_属性都没有,只能去cas服务器请求登录,
//这里有个坑,,没想到在这里没有直接出现登录页,而是调用cas服务器地址后,直接返回来了,而且会在@那里再去调用登录地址
response.sendRedirect(encodedService);
//其他的事情后续就不要再debug了,已经跟我们cas没有啥关系了,博主,debug了半天越看越懵,才发现是服务在做其他的事情,
// 我们的登录页面早就已经出现了
}
} else {
filterChain.doFilter(request, response);
}
}
}
}
}

上面的还有一个坑,就是,在用户登录成功后,回调我们的地址,第一次并不会带给我们ticket参数,而且还会走

ncodedService = this.SSOServerUrl + "/login?service=" + URLEncoder.encode(serviceUrl, "UTF-8") + "&redirect=true";
这个逻辑,并且附上casreturn属性,然后,cas服务器这回才会把ticket参数返回给我们的接口,剩下的就是下一个过滤器的事情了,慢慢来:

好了,这次有ticket了,我们来看下一个过滤器SSO Ticket Validation Filter

 public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//这里做了点事,是否为代理,博主没用这个,默认代理为null,返回true
if (this.preFilter(servletRequest, servletResponse, filterChain)) {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
//获取ticket请求参数
String ticket = CommonUtils.safeGetParameter(request, this.getArtifactParameterName());
//到这里了,分为三种情况,
//有ticket,因为你已经登录了,cas服务器登录成功返回给你了,接下来进行校验
//无ticket,可能你没有配置第一个过滤器,溜进来了
//无ticket,ticket已经校验成功后跳转回来了,用户属性已经设置到session中了,所以这次请求没有ticket了,不用去校验
if (CommonUtils.isNotBlank(ticket)) {
if (this.log.isDebugEnabled()) {
this.log.debug("Attempting to validate ticket: " + ticket);
} try {
//开始ticket票据校验,这才是这个ticket过滤器真正要做的
//constructServiceUrl这个方法不用管,就是拼接一下URL路径,把我的APPID啥的拼接上去
//validate做了挺多事,请看下一个类注释,这里先过去(大概逻辑就是去cas服务器验证ticket)
Assertion assertion = this.ticketValidator.validate(ticket, this.constructServiceUrl(request, response));
if (this.log.isDebugEnabled()) {
this.log.debug("Successfully authenticated user: " + assertion.getPrincipal().getName());
}
//看到这里没有,就是在第一个过滤器进行校验的参数,如果ticket验证成功,就会往request,及session设置属性,该属性就是_const_cas_assertion_
//该属性值则是一个用户信息map
request.setAttribute("_const_cas_assertion_", assertion);
if (this.useSession) {
request.getSession().setAttribute("_const_cas_assertion_", assertion);
}
//空方法,不用管
this.onSuccessfulValidation(request, response, assertion);
//ticket验证成功后,在进行跳转,这次是跳到我们自己的请求地址
if (this.redirectAfterValidation) {
this.log.debug("Redirecting after successful ticket validation.");
response.sendRedirect(this.constructServiceUrl(request, response));
return;
}
} catch (TicketValidationException var8) {
response.setStatus(403);
this.log.warn(var8, var8);
this.onFailedValidation(request, response);
if (this.exceptionOnValidationFailure) {
throw new ServletException(var8);
} return;
}
} filterChain.doFilter(request, response);
}
}

里面的ticket验证逻辑在此:

 public Assertion validate(String ticket, String service) throws TicketValidationException {
//此处是拼接好要调用的URL
//http://sso.jxeduyun.com/sso/,该路径是在web.xml中改ticket过滤器进行配置的SSOServerUrlPrefix
//http://sso.jxeduyun.com/sso/serviceValidate?needAttribute=true&ticket=ST-28699-qdyblKpRwc5LpLk57dRM-sso.jxeduyun.com&service=http%3A%2F%2F127.0.0.1%3A9000%2Fdsideal_yy%2FdsTyrzLogin%2FssoLogin%3FloginType%3Dweb%26from%3Dew%26appId%3D00000&appKey=00000
String validationUrl = this.constructValidationUrl(ticket, service);
if (this.log.isDebugEnabled()) {
this.log.debug("Constructing validation url: " + validationUrl);
} try {
this.log.debug("Retrieving response from server.");
//这里不用看,就是发起请求调用上面的接口,查看ticket有效性
String serverResponse = this.retrieveResponseFromServer(new URL(validationUrl), ticket);
if (serverResponse == null) {
throw new TicketValidationException("The CAS server returned no response.");
} else {
if (this.log.isDebugEnabled()) {
this.log.debug("Server response: " + serverResponse);
}
//这个不用看了,就是解析返回的cas数据,然后获取里面的用户信息,并封装成map
return this.parseResponseFromServer(serverResponse);
}
} catch (MalformedURLException var5) {
throw new TicketValidationException(var5);
}
}

因为ticket验证成功后并没有直接到下一个过滤器,而是从新请求了一次,这次不会有ticket参数了,因为session中已经有属性了,就在前几个过滤器中进行判断,在都走一次,然后才会到下面这个过滤器

 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpSession session = request.getSession(false);
Assertion assertion = (Assertion)((Assertion)(session == null ? request.getAttribute("_const_cas_assertion_") : session.getAttribute("_const_cas_assertion_"))); try {
//该过滤器的作用就是,把用户对象从session中拿出来,放到AssertionHolder里面,从而在代码中获取对象信息的时候,
//直接调用该对象即可
AssertionHolder.setAssertion(assertion);
filterChain.doFilter(servletRequest, servletResponse);
} finally {
AssertionHolder.clear();
} }

至此,cas的登录流程全部走完,不知道大家看懂多少,花了博主大概一天的时间才把源码理解通,ticket返回示例给大家一下,还有代码调用:

 失败示例:
<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
<cas:authenticationFailure code='INVALID_TICKET'>
ticket 'ST-28699-qdyblKpRwc5LpLk57dRM-sso.jxeduyun.com' not recognized
</cas:authenticationFailure>
</cas:serviceResponse>
成功示例:
<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
<cas:authenticationSuccess>
<cas:user>test</cas:user>
<cas:attributes>
<cas:multipleId>test-test-test-test-test</cas:multipleId> <cas:userId>test</cas:userId> <cas:loginName>test</cas:loginName> </cas:attributes>
</cas:authenticationSuccess>
</cas:serviceResponse>

代码调用示例:

         Assertion assertion = AssertionHolder.getAssertion();
String openId = assertion.getPrincipal().getName();
Map<String, Object> attributes = assertion.getPrincipal().getAttributes();
String userId = attributes.get("userId").toString();
String loginName = attributes.get("loginName").toString();
System.out.println("openId:"+openId);
System.out.println("userId:"+userId);
System.out.println("loginName:"+loginName);

原创不易,转载请说明出处!谢谢

cas客户端流程详解(源码解析)--单点登录的更多相关文章

  1. Java开源生鲜电商平台-盈利模式详解(源码可下载)

    Java开源生鲜电商平台-盈利模式详解(源码可下载) 该平台提供一个联合买家与卖家的一个平台.(类似淘宝购物,这里指的是食材的购买.) 平台有以下的盈利模式:(类似的平台有美菜网,食材网等) 1. 订 ...

  2. ArrayList详解-源码分析

    ArrayList详解-源码分析 1. 概述 在平时的开发中,用到最多的集合应该就是ArrayList了,本篇文章将结合源代码来学习ArrayList. ArrayList是基于数组实现的集合列表 支 ...

  3. LinkedList详解-源码分析

    LinkedList详解-源码分析 LinkedList是List接口的第二个具体的实现类,第一个是ArrayList,前面一篇文章已经总结过了,下面我们来结合源码,学习LinkedList. 基于双 ...

  4. Shiro的Filter机制详解---源码分析

    Shiro的Filter机制详解 首先从spring-shiro.xml的filter配置说起,先回答两个问题: 1, 为什么相同url规则,后面定义的会覆盖前面定义的(执行的时候只执行最后一个). ...

  5. udhcp详解源码(序)

    最近负责接入模块,包括dhcp.ipoe和pppoe等等.所以需要对dhcp和ppp这几个app的源代码进行一些分析.网上有比较好的文章,参考并补充自己的分析. 这篇udhcp详解是基于busybox ...

  6. Shiro的Filter机制详解---源码分析(转)

    Shiro的Filter机制详解 首先从spring-shiro.xml的filter配置说起,先回答两个问题: 1, 为什么相同url规则,后面定义的会覆盖前面定义的(执行的时候只执行最后一个). ...

  7. Android4.3 屏蔽HOME按键返回桌面详解(源码环境下)

    点击打开链接 首先声明我是做系统开发的(高通平台),所以下面介绍的方法并不适合应用开发者. 最经有个需求要屏蔽HOME按键返回桌面并且实现自己的功能,发现以前的方式报错用不了,上网搜索了一下,发现都是 ...

  8. Python-Flask框架之——图书管理系统 , 附详解源码和效果图 !

    该图书管理系统要实现的功能: 1. 可以通过添加窗口添加书籍或作者, 如果要添加的作者和书籍已存在于书架上, 则给出相应的提示. 2. 如果要添加的作者存在, 而要添加的书籍书架上没有, 则将该书籍添 ...

  9. RecyclerView实现瀑布流效果(图文详解+源码奉送)

    最近有时间研究了一下RecyclerView,果然功能强大啊,能实现的效果还是比较多的,那么今天给大家介绍一个用RecyclerView实现的瀑布流效果. 先来一张效果图: 看看怎么实现吧: 整体工程 ...

随机推荐

  1. Bash知识点记录

    变量的设置规则   1.  等号两边不能直接接空格符.   2. 右侧的变量内容若有空格符,可使用双引号或单引号将变量内容括起来,其中, 双引号内的特殊字符如 $ 等,可以保有原本的特性.如下所示: ...

  2. sed中使用shell变量

    假设希望在 file_to_modified 文件最后新增一行以下信息:传入 shell 脚本文件的第一个参数,以及当前时间(YYYY-MM-DD HH:MMS) date "+%Y-%m- ...

  3. Redis底层结构全了解

    第一篇文章,思来想去,写一写Redis吧,最近在深入研究它. 一丶Redis底层结构 1. redis 存储结构 redis的存储结构从外层往内层依次是redisDb.dict.dictht.dict ...

  4. 腾讯音乐Android工程师一面面试题记录,拿走不谢!

    最近参加了一次鹅厂音乐Android工程师面试,这里凭记忆记录了一些一面的面试题,希望能帮到正在面试的你! 1.Java调用函数传入实际参数时,是值传递还是引用传递? 2.单例模式的DCL方式,为什么 ...

  5. YII2.0安装教程,数据库配置前后台

    1.首先下载yii-advanced-app-2.0.6.tgz 我本地服务用的是Apache 2.解压到E:\wamp\www\yii2目录下面将目录advanced下所有文件剪切到 E:\wamp ...

  6. vulstack红队评估(三)

    一.环境搭建: ①根据作者公开的靶机信息整理 没有虚拟机密码,纯黑盒测试...一共是5台机器,目标是拿下域控获取flag文件   ②虚拟机网卡设置 centos双网卡模拟内外网: 外网:192.168 ...

  7. SourceTree使用详解(连接远程仓库,克隆,拉取,提交,推送,新建/切换/合并分支,冲突解决)

    前言: 俗话说的好工欲善其事必先利其器,Git分布式版本控制系统是我们日常开发中不可或缺的.目前市面上比较流行的Git可视化管理工具有SourceTree.Github Desktop.Tortois ...

  8. new jup在新一代中存在

    1.灰度发布服务动态路由 动态配置路由规则,实现对调用流量的精确控制.可配置基于版本.IP.自定义标签等复杂的规则.2.服务鉴权示例2需求:服务 provider-demo 只允许来自 consume ...

  9. vue-elemnt-admin源码学习

    vue-elemnt-admin源码学习 vue-element-admin是一个基于vue,element-ui的集成的管理后台.它的安装部分就不说了,按照官网的步骤一步步就可以执行了. https ...

  10. EDM邮件制作

    EDM营销(Email Direct Marketing)也叫:Email营销.电子邮件营销.是指企业向目标客户发送EDM邮件,建立同目标顾客的沟通渠道,向其直接传达相关信息,用来促进销售的一种营销手 ...