CAS-Client客户端研究--SingleSignOutFilter

本文介绍了CAS(Central Authentication Service)中的单点登出功能实现原理。通过分析SingleSignOutFilter的工作流程,包括如何记录和销毁会话,以及与SingleSignOutHttpSessionListener的配合使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!-- 

该过滤器用于实现单点登出功能,可选配置。

 -->
<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>

SingleSignOutFilter ,主要是在有ticket参数的时候,将session放到sessionMappingStorage,如果参数中存在logoutRequest,则注销session,大家可能要问了,那什么时候去注销sessionMappingStorage的东西呢?这是靠SingleSignOutHttpSessionListener来实现的,当有session被销毁的时候,触发将sessionMappingStorage中对应sessionid中的数据删除。所以在配置单点登出的时候,一定要配置这个监听器,否则客户端很容易导致内存溢出的。让我们先来看看SingleSignOutFilter 的整体逻辑。

那么这个是在什么时候会触发呢,这个是在你登陆的任意客户端,调用https://xxx:8443/logout,这个取得cookie里面的TGT数据,找到TGT中关联的所有ST对应的地址,向每个地址方式一个http请求,并传递logoutRequest参数。

配置web.xml




我们来看看源代码是怎么实现的吧:

    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {  
          // 转换参数  
        final HttpServletRequest request = (HttpServletRequest) servletRequest;  
        //判断参数中是否具有artifactParameterName属性指定的参数名称,默认是ticket  
          if (handler.isTokenRequest(request)) {  
            // 如果存在,在本地sessionMappingStorage中记录session。  
              handler.recordSession(request);   
          } else if (handler.isLogoutRequest(request)) {//判断是否具有logoutParameterName参数指定的参数,默认参数名称为logoutRequest  
            // 如果存在,则在sessionMappingStorage中删除记录,并注销session。  
            handler.destroySession(request);  
              // 注销session后,立刻停止执行后面的过滤器  
              return;  
          } else {  
              log.trace("Ignoring URI " + request.getRequestURI());  
          }  
          //条件都不满足,继续执行下面的过滤器  
          filterChain.doFilter(servletRequest, servletResponse);  
      }  

public final class SingleSignOutHandler {
...
    /**
     * Determines whether the given request contains an authentication token.
     *
     * @param request HTTP reqest.
     *
     * @return True if request contains authentication token, false otherwise.
     */
    public boolean isTokenRequest(final HttpServletRequest request) {
        return CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.artifactParameterName));
    }

    /**
     * Determines whether the given request is a CAS logout request.
     *
     * @param request HTTP request.
     *
     * @return True if request is logout request, false otherwise.
     */
    public boolean isLogoutRequest(final HttpServletRequest request) {
        return "POST".equals(request.getMethod()) && !isMultipartRequest(request) &&
            CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.logoutParameterName));
    }

    /**
     * Associates a token request with the current HTTP session by recording the mapping
     * in the the configured {@link SessionMappingStorage} container.
     * 
     * @param request HTTP request containing an authentication token.
     */
 public void recordSession(final HttpServletRequest request) {
        final HttpSession session = request.getSession(true);

        final String token = CommonUtils.safeGetParameter(request, this.artifactParameterName);
       
        try {
            this.sessionMappingStorage.removeBySessionById(session.getId());
        } catch (final Exception e) {
            // ignore if the session is already marked as invalid.  Nothing we can do!
        }
        sessionMappingStorage.addSessionById(token, session);
    }
   
    /**
     * Destroys the current HTTP session for the given CAS logout request.
     *
     * @param request HTTP request containing a CAS logout message.
     */
    public void destroySession(final HttpServletRequest request) {
        final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName);
               
        final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex");
        if (CommonUtils.isNotBlank(token)) {
            final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token);

            if (session != null) {
                String sessionID = session.getId();
               
                try {
                    session.invalidate();
                } catch (final IllegalStateException e) {
                    log.debug("Error invalidating session.", e);
                }
            }
        }
    }
....
}



可以使用Spring Security CAS扩展来实现。在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>org.springframework.security.extensions</groupId> <artifactId>spring-security-cas</artifactId> <version>1.0.7.RELEASE</version> </dependency> ``` 然后在application.properties文件中添加以下配置: ``` # CAS server URL cas.server.url=https://cas.example.com/cas # CAS server login URL cas.server.login.url=https://cas.example.com/cas/login # CAS server logout URL cas.server.logout.url=https://cas.example.com/cas/logout # CAS service URL cas.service.url=http://localhost:8080/login/cas # CAS service name cas.service.name=MyApp # CAS service login URL cas.service.login.url=http://localhost:8080/login # CAS service logout URL cas.service.logout.url=http://localhost:8080/logout # CAS service validate URL cas.service.validate.url=https://cas.example.com/cas/serviceValidate # CAS service ticket parameter name cas.service.ticket.parameterName=ticket # CAS service renew parameter name cas.service.renew.parameterName=renew # CAS service gateway parameter name cas.service.gateway.parameterName=gateway # CAS service artifact parameter name cas.service.artifact.parameterName=artifact # CAS service proxy callback URL cas.service.proxy.callbackUrl=http://localhost:8080/proxyCallback # CAS service proxy callback parameter name cas.service.proxy.callbackParameterName=pgtIou # CAS service proxy granting ticket parameter name cas.service.proxy.grantingTicket.parameterName=pgtIou # CAS service proxy granting ticket storage class cas.service.proxy.grantingTicket.storageClass=org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl # CAS service proxy granting ticket storage file cas.service.proxy.grantingTicket.storageFile=/tmp/cas-proxy-granting-tickets # CAS service proxy granting ticket storage clean interval cas.service.proxy.grantingTicket.storageCleanInterval=3600000 # CAS service proxy granting ticket storage clean up cas.service.proxy.grantingTicket.storageCleanUp=true # CAS service proxy granting ticket storage clean up interval cas.service.proxy.grantingTicket.storageCleanUpInterval=3600000 # CAS service proxy granting ticket storage clean up max age cas.service.proxy.grantingTicket.storageCleanUpMaxAge=7200000 ``` 然后在Spring Boot应用程序中添加以下配置类: ``` @Configuration @EnableWebSecurity @EnableCasSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CasAuthenticationEntryPoint casAuthenticationEntryPoint; @Autowired private CasAuthenticationProvider casAuthenticationProvider; @Autowired private SingleSignOutFilter singleSignOutFilter; @Autowired private CasAuthenticationFilter casAuthenticationFilter; @Autowired private CasProperties casProperties; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .exceptionHandling() .authenticationEntryPoint(casAuthenticationEntryPoint) .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .addLogoutHandler(new SingleSignOutHandler(casProperties.getServer().getLogoutUrl())) .and() .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) .addFilter(casAuthenticationFilter); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(casAuthenticationProvider); } @Bean public ServiceProperties serviceProperties() { ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setService(casProperties.getService().getUrl()); serviceProperties.setSendRenew(false); return serviceProperties; } @Bean public CasAuthenticationEntryPoint casAuthenticationEntryPoint() { CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint(); casAuthenticationEntryPoint.setLoginUrl(casProperties.getServer().getLoginUrl()); casAuthenticationEntryPoint.setServiceProperties(serviceProperties()); return casAuthenticationEntryPoint; } @Bean public CasAuthenticationProvider casAuthenticationProvider() { CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider(); casAuthenticationProvider.setAuthenticationUserDetailsService(new UserDetailsServiceImpl()); casAuthenticationProvider.setServiceProperties(serviceProperties()); casAuthenticationProvider.setTicketValidator(new Cas30ServiceTicketValidator(casProperties.getServer().getUrl())); casAuthenticationProvider.setKey("casAuthenticationProviderKey"); return casAuthenticationProvider; } @Bean public SingleSignOutFilter singleSignOutFilter() { SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); singleSignOutFilter.setCasServerUrlPrefix(casProperties.getServer().getUrl()); singleSignOutFilter.setIgnoreInitConfiguration(true); return singleSignOutFilter; } @Bean public CasAuthenticationFilter casAuthenticationFilter() { CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter(); casAuthenticationFilter.setAuthenticationManager(authenticationManager()); casAuthenticationFilter.setFilterProcessesUrl("/login/cas"); return casAuthenticationFilter; } } ``` 最后,在Spring Boot应用程序中添加以下服务类: ``` @Service public class UserDetailsServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> { @Override public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException { String username = token.getName(); List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); return new User(username, "", authorities); } } ``` 现在,您可以使用Spring Boot应用程序调用CAS客户端自动配置支持来解析票据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值