`
pengfeifei26
  • 浏览: 244414 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

cas 客户端自定义页面-客户端

    博客分类:
  • cas
 
阅读更多
1、web-xml修改filter:
 <listener>
     <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>
 </listener>
<!-- CAS -->
 <filter>
     <filter-name>CAS Single Sign Out Filter</filter-name>
     <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>
 </filter>  
    <filter> 
  <filter-name>CAS Filter</filter-name> 
  <filter-class>com.cas.client.validation.RemoteAuthenticationFilter</filter-class> 
  <init-param> 
   <param-name>localLoginUrl</param-name> 
   <param-value>http://localhost:8080/c1/login.jsp</param-value> 
  </init-param>
  <init-param>
         <param-name>casServerLoginUrl</param-name>
         <param-value>https://xuhang-PC:8443/cas/remoteLogin</param-value>
     </init-param>
  <init-param> 
   <param-name>edu.yale.its.tp.cas.client.filter.validateUrl</param-name> 
   <param-value>https://xuhang-PC:8443/cas/serviceValidate</param-value> 
  </init-param> 
  <init-param> 
   <param-name>edu.yale.its.tp.cas.client.filter.serverName</param-name>
   <param-value>localhost:8080</param-value>
  </init-param>
 </filter>
    
 <filter-mapping>
     <filter-name>CAS Single Sign Out Filter</filter-name>
     <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping> 
  <filter-name>CAS Filter</filter-name> 
  <url-pattern>/*</url-pattern> 
 </filter-mapping>
<!-- END CAS --> 
 

2、com.cas.client.validation.RemoteAuthenticationFilter代码如下:
com.cas.client.validation.RemoteAuthenticationFilter是修改edu.yale.its.tp.cas.client.filter.CASFilter而来,改动的函数有:
public void init(FilterConfig config) throws ServletException {
        casLogin = config.getInitParameter(LOGIN_INIT_PARAM);
        casValidate = config.getInitParameter(VALIDATE_INIT_PARAM);
        casServiceUrl = config.getInitParameter(SERVICE_INIT_PARAM);
        String casAuthorizedProxy = config.getInitParameter(AUTHORIZED_PROXY_INIT_PARAM);
        casRenew = Boolean.valueOf(config.getInitParameter(RENEW_INIT_PARAM)).booleanValue();
        casServerName = config.getInitParameter(SERVERNAME_INIT_PARAM);
        casProxyCallbackUrl = config.getInitParameter(PROXY_CALLBACK_INIT_PARAM);
        wrapRequest = Boolean.valueOf(config.getInitParameter(WRAP_REQUESTS_INIT_PARAM)).booleanValue();
        casGateway = Boolean.valueOf(config.getInitParameter(GATEWAY_INIT_PARAM)).booleanValue();

        if (casGateway && Boolean.valueOf(casRenew).booleanValue()) {
            throw new ServletException("gateway and renew cannot both be true in filter configuration");
        }
        if (casServerName != null && casServiceUrl != null) {
            throw new ServletException("serverName and serviceUrl cannot both be set: choose one.");
        }
        if (casServerName == null && casServiceUrl == null) {
            throw new ServletException("one of serverName or serviceUrl must be set.");
        }
        if (casServiceUrl != null){
            if (! (casServiceUrl.startsWith("https://")|| (casServiceUrl.startsWith("http://") ))){
                throw new ServletException("service URL must start with http:// or https://; its current value is [" + casServiceUrl + "]");
            }
        }
        
        if (casValidate == null){
            throw new ServletException("validateUrl parameter must be set.");
        }
        if (! casValidate.startsWith("https://")){
            throw new ServletException("validateUrl must start with https://, its current value is [" + casValidate + "]");
        }
        
        if (casAuthorizedProxy != null){
            
            // parse and remember authorized proxies
            StringTokenizer casProxies =
                new StringTokenizer(casAuthorizedProxy);
            while (casProxies.hasMoreTokens()) {
                String anAuthorizedProxy = casProxies.nextToken();
                if (!anAuthorizedProxy.startsWith("https://")){
                    throw new ServletException("CASFilter initialization parameter for authorized proxies " +
                            "must be a whitespace delimited list of authorized proxies.  " +
                            "Authorized proxies must be secure (https) addresses.  This one wasn't: [" + anAuthorizedProxy + "]");
                }
                this.authorizedProxies.add(anAuthorizedProxy);
            }
        }
        
        if (log.isDebugEnabled()){
         log.debug(("CASFilter initialized as: [" + toString() + "]"));
        }
        
        /*
         * RemoteAuthentication 新增部分
         */
        casServerLoginUrl = config.getInitParameter("casServerLoginUrl");
        log.trace("Loaded CasServerLoginUrl parameter: " + this.casServerLoginUrl);
        localLoginUrl = config.getInitParameter("localLoginUrl");
        log.trace("Loaded LocalLoginUrl parameter: " + this.localLoginUrl);
    }

    public void doFilter(ServletRequest request,ServletResponse response,FilterChain filterChain) throws ServletException, IOException {

  if (log.isTraceEnabled()){
   log.trace("entering doFilter()");
  }

        // make sure we've got an HTTP request
        if (!(request instanceof HttpServletRequest)
                || !(response instanceof HttpServletResponse)) {
         log.error("doFilter() called on a request or response that was not an HttpServletRequest or response.");
      throw new ServletException("CASFilter protects only HTTP resources");
        }

        // Is this a request for the proxy callback listener?  If so, pass
        // it through
        if (casProxyCallbackUrl != null
            && casProxyCallbackUrl.endsWith(((HttpServletRequest) request).getRequestURI())
            && request.getParameter("pgtId") != null
            && request.getParameter("pgtIou") != null) {
            log.trace("passing through what we hope is CAS's request for proxy ticket receptor.");
            filterChain.doFilter(request, response);
            return;
        }

        // Wrap the request if desired
        if (wrapRequest) {
         log.trace("Wrapping request with CASFilterRequestWrapper.");
            request = new CASFilterRequestWrapper((HttpServletRequest) request);
        }

        HttpSession session = ((HttpServletRequest) request).getSession();

        // if our attribute's already present and valid, pass through the filter chain
        CASReceipt receipt = (CASReceipt) session.getAttribute(CAS_FILTER_RECEIPT);
        if (receipt != null && isReceiptAcceptable(receipt)) {
         log.trace("CAS_FILTER_RECEIPT attribute was present and acceptable - passing  request through filter..");
            filterChain.doFilter(request, response);
            return;
        }

        // otherwise, we need to authenticate via CAS
        String ticket = request.getParameter("ticket");

        // no ticket?  abort request processing and redirect
        if (ticket == null || ticket.equals("")) {
   log.trace("CAS ticket was not present on request.");
   /*
          * RemoteAuthentication 新增部分
          */
   if (localLoginUrl!=null&&!"".equals(localLoginUrl)){
    // 如果访问路径为localLoginUrl且带有validated参数则跳过
          URL url = new URL(localLoginUrl);
          final boolean isValidatedLocalLoginUrl = ((HttpServletRequest)request).getRequestURI().endsWith(url.getPath()) && CommonUtils.isNotBlank(request.getParameter("validated"));
          if (!isValidatedLocalLoginUrl){
           if (this.casGateway) {
                  log.debug("setting gateway attribute in session");
                  ((HttpServletRequest)request).getSession(true).setAttribute(CONST_CAS_GATEWAY, "yes");
              }

              final String serviceUrl = constructServiceUrl((HttpServletRequest)request, (HttpServletResponse)response);

              if (log.isDebugEnabled()) {
                  log.debug("Constructed service url: " + serviceUrl);
              }

              String urlToRedirectTo = CommonUtils.constructRedirectUrl(
                      this.casServerLoginUrl, getServiceParameterName(),
                      serviceUrl, this.casRenew, this.casGateway);

              // 加入localLoginUrl
              urlToRedirectTo += (urlToRedirectTo.contains("?") ? "&" : "?") + "loginUrl=" + URLEncoder.encode(localLoginUrl, "utf-8");

              if (log.isDebugEnabled()) {
                  log.debug("redirecting to \"" + urlToRedirectTo + "\"");
              }
              
              ((HttpServletResponse)response).sendRedirect(urlToRedirectTo);
              return;
          }else{
           // continue processing the request
              filterChain.doFilter(request, response);
              return;
          }
   }else{
    // did we go through the gateway already?
             boolean didGateway = Boolean.valueOf((String) session.getAttribute(CAS_FILTER_GATEWAYED)).booleanValue();

             if (casLogin == null) {
              //TODO: casLogin should probably be ensured to not be null at filter initialization. -awp9
              log.fatal("casLogin was not set, so filter cannot redirect request for authentication.");
                 throw new ServletException(
                     "When CASFilter protects pages that do not receive a 'ticket' "
                         + "parameter, it needs a edu.yale.its.tp.cas.client.filter.loginUrl "
                         + "filter parameter");
             }
             if (!didGateway) {
              log.trace("Did not previously gateway.  Setting session attribute to true.");
                 session.setAttribute(CAS_FILTER_GATEWAYED, "true");
                 redirectToCAS((HttpServletRequest) request,(HttpServletResponse) response);
                 // abort chain
                 return;
             } else {
              log.trace("Previously gatewayed.");
                 // if we should be logged in, make sure validation succeeded
                 if (casGateway || session.getAttribute(CAS_FILTER_USER) != null) {
                  log.trace("casGateway was true and CAS_FILTER_USER set: passing request along filter chain.");
                     // continue processing the request
                     filterChain.doFilter(request, response);
                     return;
                 } else {
                     // unknown state... redirect to CAS
                     session.setAttribute(CAS_FILTER_GATEWAYED,"true");
                     redirectToCAS((HttpServletRequest) request,(HttpServletResponse) response);
                     // abort chain
                     return;
                 }
             }
   }
        }

        try {
            receipt = getAuthenticatedUser((HttpServletRequest) request);
        } catch (CASAuthenticationException e) {
            log.error(e);
            throw new ServletException(e);
        }

        if (! isReceiptAcceptable(receipt)){
            throw new ServletException("Authentication was technically successful but rejected as a matter of policy. [" + receipt + "]");
        }
        
        // Store the authenticated user in the session
        if (session != null) { // probably unnecessary
            session.setAttribute(CAS_FILTER_USER, receipt.getUserName());
            session.setAttribute(RemoteAuthenticationFilter.CAS_FILTER_RECEIPT, receipt);
            // don't store extra unnecessary session state
            session.removeAttribute(CAS_FILTER_GATEWAYED);
        }
        if (log.isTraceEnabled()){
   log.trace("validated ticket to get authenticated receipt [" + receipt + "], now passing request along filter chain.");
        }
        
        // continue processing the request
        filterChain.doFilter(request, response);
        log.trace("returning from doFilter()");
    }


3、登录jsp:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>远程CAS客户端登陆页面</title>
    <script type="text/javascript">
    function getParam(name) {
        var queryString = window.location.search;
        var param = queryString.substr(1, queryString.length - 1).split("&");
        for (var i = 0; i < param.length; i++) {
            var keyValue = param[i].split("=");
            if (keyValue[0] == name) return keyValue[1];
        }
        return null;
    }
    function init() {
        // 显示异常信息
        var error = getParam("errorMessage");
        if (error) {
            document.getElementById("errorMessage").innerHTML = decodeURIComponent(error);
        }
        // 注入service
        var service = getParam("service");
        if (service)
            document.getElementById("service").value = decodeURIComponent(service);
        else
            document.getElementById("service").value = location.href;
    }
    </script>
</head>
<body>
    <h1>远程CAS客户端登陆页面</h1>
    <% if (request.getSession().getAttribute("edu.yale.its.tp.cas.client.filter.user") == null) { %>
    <div id="errorMessage"></div>
     <form id="myLoginForm" action="https://xuhang-PC:8443/cas/remoteLogin" method="post">
            <input type="hidden" id="service" name="service" value="">
            <input type="hidden" name="loginUrl" value="http://localhost:8080/c1/login.jsp">
            <input type="hidden" name="submit" value="true" />
            <input type="hidden" name="lt" value="${loginTicket}" />
            <table>
                <tr>
                    <td>用户名:</td>
                    <td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>密&nbsp;&nbsp;码:</td>
                    <td><input type="password" name="password"></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="登陆" /></td>
                </tr>
            </table>
  </form>
  <script type="text/javascript">init();</script>
    <% } else { %>
        <div class="welcome">您好:<%= (String)request.getSession().getAttribute("edu.yale.its.tp.cas.client.filter.user") %></div>
        <div id="logout">
            <a href="https://xuhang-PC:8443/cas/remoteLogout?service=http://localhost:8080/c1/login.jsp">单点登出</a>
        </div>
 <% } %>
</body>
</html>
分享到:
评论

相关推荐

    让CAS支持客户端自定义登陆页面----服务器篇--.doc编程资料

    让CAS支持客户端自定义登陆页面----服务器篇--.doc

    让CAS支持客户端自定义登陆页面----服务器篇.doc

    让CAS支持客户端自定义登陆页面----服务器篇.doc

    CAS客户端自定义核心过滤器

    CAS客户端自定义核心过滤器,继承CAS的AbstractCasFilter自定义AuthenticationFilter

    让CAS支持客户端自定义登陆页面----服务器篇--.doc

    ### 让CAS支持客户端自定义登录页面——服务器端配置详解 #### 一、背景与目的 随着企业级应用系统的不断扩展和发展,身份认证系统(如CAS)的安全性和灵活性变得尤为重要。CAS(Central Authentication Service)...

    让CAS支持客户端自定义登陆页面----服务器篇-.pdf

    本文主要介绍如何让CAS(Central Authentication Service)支持客户端自定义登录页面,主要集中在服务器端的修改。CAS是一种开源的身份验证框架,它提供单点登录(SSO)功能,通常用于集中管理多个应用系统的用户...

    让CAS支持客户端自定义登陆页面——服务器篇[参考].pdf

    "CAS支持客户端自定义登陆页面——服务器篇" 为了让CAS支持客户端自定义登陆页面,需要在服务器端进行修改。首先,需要在/WEB-INF/web.xml文件中增加一个/remoteLogin的映射,以便将请求指向新的登陆页面。其次,...

    CAS-3.2.1自定义客户端登录界面----完整篇

    标题中的"CAS-3.2.1自定义客户端登录界面"指的是中央认证服务(Central Authentication Service,CAS)的3.2.1版本中关于自定义客户端登录界面的实践。CAS是一种开源的身份验证协议,用于在网络上为用户提供单点登录...

    CAS单点登录(SSO)服务端自定义认证+CAS客户端配置+CAS完整使用文档+CAS4.2.7 cas-serv服务端源码 cas-client客户端源码

    本压缩包提供了CAS服务端自定义认证的实现,以及CAS客户端的配置示例,适用于需要构建安全认证系统的IT专业人员。以下是对压缩包中内容的详细解释: 1. **CAS服务器端自定义认证**: CAS服务端的核心功能在于验证...

    cas 自定义登录页面

    在实际的企业环境中,根据业务需求,我们可能需要对默认的CAS登录页面进行自定义,以提供更符合品牌形象或用户体验的界面。下面将详细讲解如何配置和实现CAS的自定义登录页面。 一、CAS自定义登录页面概述 CAS的...

    整合spring+springWebMVC+cas客户端

    在IT行业中,集成Spring、Spring Web MVC和CAS客户端是一项常见的任务,主要用于构建安全的Web应用程序。下面将详细解释这些技术及其整合过程。 首先,Spring是一个开源的Java框架,它简化了开发过程,提供了依赖...

    让CAS支持客户端自定义登陆页面——服务器篇.docx

    ### 让CAS支持客户端自定义登录页面——服务器篇 #### 概述 本文档主要介绍如何在CAS(Central Authentication Service)系统中实现客户端自定义登录页面的功能,并且着重讲解服务器端的修改步骤与注意事项。CAS...

    cas-server-3.4.10-release和cas-client-3.2.1-release两个

    CAS客户端则部署在需要保护的应用服务器上,它负责引导用户到CAS服务器进行认证,接收和验证服务器返回的认证票据,以及实现SSO的逻辑。在这个版本中,客户端可能包含以下组件: 1. **过滤器**:在应用的Web容器中...

    让CAS支持客户端自定义登陆页面——客户端篇

    通过以上步骤,你可以使CAS客户端应用支持自定义登录页面,从而提供更个性化的用户体验。记住,每个CAS服务器的实现和配置可能会有所不同,因此在实际操作中需要根据具体情况进行调整。同时,为了确保安全性,务必...

    Cas5.2.6(cas-overlay-template-5.2.6)服务端

    集成完成后,可以通过CAS客户端(如浏览器插件或应用配置)进行测试,确保单点登录功能正常工作。同时,CAS提供了丰富的日志记录和调试选项,有助于定位问题。 总之,CAS 5.2.6服务端的集成和搭建涉及到了安全、...

    cas客户端jar包

    在这个场景中,"cas客户端jar包"是指用于与CAS服务器通信的Java库,方便开发者集成到他们的Java应用程序中,实现单点登录功能。 首先,我们需要了解CAS客户端的主要组件和工作原理。当用户尝试访问一个受CAS保护的...

    cas-server-3.4.10-release和cas-client-3.2.1-release

    接下来是`cas-client-3.2.1-release`,它是CAS客户端的发布包,用于集成到各个应用系统中,实现对CAS服务器的调用。这个版本包含客户端库、配置示例和其他相关资源。客户端的主要功能有: 1. **票证验证**:客户端...

    cas-client-3.1.12-release.zip

    《CAS客户端3.1.12版本详解》 CAS(Central Authentication Service)是 Yale 大学开发的一个开源项目,主要用于实现单点登录(Single Sign-On, SSO)。它是一个基于Web的认证协议,旨在简化用户对多个应用系统的...

Global site tag (gtag.js) - Google Analytics