收藏 分销(赏)

CAS实现 SSO的原理和方法简介.doc

上传人:s4****5z 文档编号:8819973 上传时间:2025-03-03 格式:DOC 页数:10 大小:115.50KB 下载积分:10 金币
下载 相关 举报
CAS实现 SSO的原理和方法简介.doc_第1页
第1页 / 共10页
CAS实现 SSO的原理和方法简介.doc_第2页
第2页 / 共10页


点击查看更多>>
资源描述
CAS实现 SSO的原理和方法简介 1. 了解一下cas 实现single sign out的原理,如图所示:                                         图一 演示了单点登陆的工作原理。 当一个web浏览器登录到应用服务器时,应用服务器(application)会检测用户的session,如果没有session,则应用服务器会把url跳转到CAS server上,要求用户登录,用户登录成功后,CAS server会记请求的application的url和该用户的sessionId(在应用服务器跳转url时,通过参数传给CAS server)。此时在CAS服务器会种下TGC Cookie值到webbrowser.拥有该TGC Cookie的webbrowser可以无需登录进入所有建立sso服务的应用服务器application。                                     图二 演示了单点登出的工作原理。 当一个web浏览器要求登退应用服务器,应用服务器(application)会把url跳转到CAS server上的 /cas/logout url资源上, CAS server接受请求后,会检测用户的TCG Cookie,把对应的session清除,同时会找到所有通过该TGC sso登录的应用服务器URL提交请求,所有的回调请求中,包含一个参数logoutRequest,内容格式如下: <samlp:LogoutRequest ID="[RANDOM ID]" Version="2.0" IssueInstant="[CURRENT DATE/TIME]"> <saml:NameID>@NOT_USED@</saml:NameID> <samlp:SessionIndex>[SESSION IDENTIFIER]</samlp:SessionIndex> </samlp:LogoutRequest> 所有收到请求的应用服务器application会解析这个参数,取得sessionId,根据这个Id取得session后,把session删除。 这样就实现单点登出的功能。 2. 结合源代码来讲述一下内部的代码怎么实现的 首先,要实现SSO在 应用服务器application端的web.xml要加入以下配置 <filter>    <filter-name>CAS Single Sign Out Filter</filter-name>    <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class> </filter> <filter-mapping>    <filter-name>CAS Single Sign Out Filter</filter-name>    <url-pattern>/*</url-pattern> </filter-mapping> <listener>     <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class> </listener> 注:如果有配置CAS client Filter,则CAS Single Sign Out Filter 必须要放到CAS client Filter之前。 配置部分的目的是在CAS server回调所有的application进行单点登出操作的时候,需要这个filter来实现session清楚。 主要代码如下: org.jasig.cas.client.session.SingleSignOutFilter public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain  filterChain) throws IOException, ServletException {          final HttpServletRequest request = (HttpServletRequest) servletRequest;              if ("POST".equals(request.getMethod())) {               final String logoutRequest = request.getParameter("logoutRequest");                 if (CommonUtils.isNotBlank(logoutRequest)) {                   if (log.isTraceEnabled()) {                     log.trace ("Logout request=[" + logoutRequest + "]");                  }                  //从xml中解析 SessionIndex key值                  final String sessionIdentifier = XmlUtils.getTextForElement(logoutRequest, "SessionIndex");                    if (CommonUtils.isNotBlank(sessionIdentifier)) {                          //根据sessionId取得session对象                      final HttpSession session = SESSION_MAPPING_STORAGE.removeSessionByMappingId(sessionIdentifier);                        if (session != null) {                          String sessionID = session.getId();                            if (log.isDebugEnabled()) {                              log.debug ("Invalidating session [" + sessionID + "] for ST [" + sessionIdentifier + "]");                          }                                                    try {                   //让session失效                              session.invalidate();                          } catch (final IllegalStateException e) {                              log.debug(e,e);                         }                     }                    return;                  }             }          } else {//get方式 表示登录,把session对象放到 SESSION_MAPPING_STORAGE(map对象中)              final String artifact = request.getParameter(this.artifactParameterName);              final HttpSession session = request.getSession();                           if (log.isDebugEnabled() && session != null) {                 log.debug("Storing session identifier for " + session.getId());              }              if (CommonUtils.isNotBlank(artifact)) {                  SESSION_MAPPING_STORAGE.addSessionById(artifact, session);              }          }          filterChain.doFilter(servletRequest, servletResponse);      } SingleSignOutHttpSessionListener实现了javax.servlet.http.HttpSessionListener接口,用于监听session销毁事件 public final class SingleSignOutHttpSessionListener implements HttpSessionListener {       private Log log = LogFactory.getLog(getClass());          private SessionMappingStorage SESSION_MAPPING_STORAGE;              public void sessionCreated(final HttpSessionEvent event) {           // nothing to do at the moment       }        //session销毁时      public void sessionDestroyed(final HttpSessionEvent event) {          if (SESSION_MAPPING_STORAGE == null) {//如果为空,创建一个sessionMappingStorage 对象              SESSION_MAPPING_STORAGE = getSessionMappingStorage();          }          final HttpSession session = event.getSession();//取得当然要销毁的session对象                    if (log.isDebugEnabled()) {              log.debug("Removing HttpSession: " + session.getId());          }          //从SESSION_MAPPING_STORAGE map根据sessionId移去session对象          SESSION_MAPPING_STORAGE.removeBySessionById(session.getId());      }      protected static SessionMappingStorage getSessionMappingStorage() {          return SingleSignOutFilter.getSessionMappingStorage();      }  } 3 CAS server端回调是怎么实现的 先来看一下配置,我们知道CAS server所有的用户登录,登出操作,都是由CentralAuthenticationServiceImpl对象来管理。 我们就先把到CentralAuthenticationServiceImpl的spring配置,在applicationContext.xml文件中 <!-- CentralAuthenticationService -->     <bean id="centralAuthenticationService" class="org.jasig.cas.CentralAuthenticationServiceImpl"         p:ticketGrantingTicketExpirationPolicy-ref="grantingTicketExpirationPolicy"         p:serviceTicketExpirationPolicy-ref="serviceTicketExpirationPolicy"         p:authenticationManager-ref="authenticationManager"         p:ticketGrantingTicketUniqueTicketIdGenerator-ref="ticketGrantingTicketUniqueIdGenerator"         p:ticketRegistry-ref="ticketRegistry"             p:servicesManager-ref="servicesManager"             p:persistentIdGenerator-ref="persistentIdGenerator"         p:uniqueTicketIdGeneratorsForService-ref="uniqueIdGeneratorsMap" /> 配置使用了spring2.0的xsd。CentralAuthenticationServiceImpl有一个属性叫uniqueTicketIdGeneratorsForService,它是一个map对象 它的key值是所有实现org.jasig.cas.authentication.principal.Service接口的类名,用于保存Principal对象和进行单点登出回调 4 TGC ticket的产生 application server时使用 value值为org.jasig.cas.util.DefaultUniqueTicketIdGenerator对象,用于生成唯一的TGC ticket。 该属性引用的uniqueIdGeneratorsMap bean在uniqueIdGenerators.xml配置文件中。 <util:map id="uniqueIdGeneratorsMap">         <entry             key="org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl"             value-ref="serviceTicketUniqueIdGenerator" />         <entry             key="org.jasig.cas.support.openid.authentication.principal.OpenIdService"             value-ref="serviceTicketUniqueIdGenerator" />         <entry             key="org.jasig.cas.authentication.principal.SamlService"             value-ref="samlServiceTicketUniqueIdGenerator" />         <entry             key="org.jasig.cas.authentication.principal.GoogleAccountsService"             value-ref="serviceTicketUniqueIdGenerator" />     </util:map> 那CentralAuthenticationServiceImpl是怎么调用的呢? 我们跟踪一下代码,在创建ticket的方法 public String createTicketGrantingTicket(final Credentials credentials)中 可以找到以下这样一段代码:          //创建 TicketGrantingTicketImpl 实例             final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(                  this.ticketGrantingTicketUniqueTicketIdGenerator                      .getNewTicketId(TicketGrantingTicket.PREFIX),                  authentication, this.ticketGrantingTicketExpirationPolicy);          //并把该对象保存到 ticketRegistry中 7        this.ticketRegistry.addTicket(ticketGrantingTicket); 5 TGC ticket 的销毁 ticketRegistry对象保存了创建的TicketGrantingTicketImpl对象,下面我们看一下当ticket销毁的时候,会做什么 代码如下:       public void destroyTicketGrantingTicket(final String ticketGrantingTicketId) {           Assert.notNull(ticketGrantingTicketId);              if (log.isDebugEnabled()) {               log.debug("Removing ticket [" + ticketGrantingTicketId                   + "] from registry.");           }       //从 ticketRegistry对象中,取得TicketGrantingTicket对象           final TicketGrantingTicket ticket = (TicketGrantingTicket) this.ticketRegistry              .getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);            if (ticket == null) {              return;          }            if (log.isDebugEnabled()) {              log.debug("Ticket found.  Expiring and then deleting.");          }          ticket.expire();//调用expire()方法,让ticket过期失效          this.ticketRegistry.deleteTicket(ticketGrantingTicketId);//从ticketRegistry中删除的ticket 对象     } 我们看到,它是从ticketRegistry对象中取得TicketGrantingTicket对象后,调用expire方法。接下来,要关心的就是expire方法做什么事情       public synchronized void expire() {           this.expired.set(true);           logOutOfServices(); }     private void logOutOfServices() {          for (final Entry<String, Service> entry : this.services.entrySet()) {              entry.getValue().logOutOfService(entry.getKey());          }     } 从代码可以看到,它是遍历每个 Service对象,并执行logOutOfService方法,参数是String sessionIdentifier 现在我们可以对应到它存放的Service就是在uniqueIdGeneratorsMap bean定义中的那些实现类 因为logOutOfService方法的实现,所有实现类都是由它们继承的抽象类AbstractWebApplicationService来实现,我们来看一下 AbstractWebApplicationService的logOutOfService方法,就可以最终找出,实现SSO的真正实现代码,下面是主要代码片段:    public synchronized boolean logOutOfService(final String sessionIdentifier) {           if (this.loggedOutAlready) {              return true;           }             LOG.debug("Sending logout request for: " + getId());           //组装 logoutRequest参数内容           final String logoutRequest = "<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""              + GENERATOR.getNewTicketId("LR")             + "\" Version=\"2.0\" IssueInstant=\"" + SamlUtils.getCurrentDateAndTime()             + "\"><saml:NameID  xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\">@NOT_USED@</saml:NameID><samlp:SessionIndex>"            + sessionIdentifier + "</samlp:SessionIndex></samlp:LogoutRequest>";       this.loggedOutAlready = true;       //回调所有的application,getOriginalUrl()是取得回调的application url        if (this.httpClient != null) {            return this.httpClient.sendMessageToEndPoint(getOriginalUrl(), logoutRequest);         }                return false;    } 至此,已经通过源代码把 CAS实现 single sign out的实现原理和方法完整叙述了一遍
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传

当前位置:首页 > 包罗万象 > 大杂烩

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服