cas客户端单点登录流程源码解析

后端 潘老师 4个月前 (12-16) 98 ℃ (0)

本文主要讲解关于cas客户端单点登录流程源码解析相关内容,让我们来一起学习下吧!

博主之前一直使用了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>

博主用的不是官方的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*tnr]", "");
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客户端单点登录流程源码解析相关的全部内容,希望对你有帮助。欢迎持续关注潘子夜个人博客(www.panziye.com),学习愉快哦!


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/back/12581.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】