---
title: "让CAS支持客户端自定义登陆页面——服务器篇 "
author: "yeminping"
date: "2009-06-19T16:40:25Z"
tags: []
slug: "cas"
draft: false
lastmod: "2009-06-19T16:40:25Z"
id: 411712
url: "https://yeminping.iteye.com/blog/411712"
---

修改需要基于几个基本原则：

1. 不影响原有统一登陆界面功能
2. 客户端应尽量保持简单
3. 尽量保证原有功能的完整性和安全性

对于第三点，必须事先说明：将登陆页面放到客户端本身就是降低了CAS安全性，这意味着作为服务向外发布的CAS服务器中的用户密码有可能由于客户端的不安全性而导致泄露，整个CAS系统成为了一个“水桶形态”，整个CAS体系的安全性将取决于所有客户端中安全性最低的一个 。这也是CAS官方一直不推荐的方式。

接下来我们讲解服务器端修改的详细过程：

首先，修改/WEB-INF/web.xml，为cas增加一个/remoteLogin的映射：

&lt;servlet-mapping&gt;  
    &lt;servlet-name&gt;cas&lt;/servlet-name&gt;  
    &lt;url-pattern&gt;/remoteLogin &lt;/url-pattern&gt;  
&lt;/servlet-mapping&gt;

然后修改cas-servlet.xml文件，增加我们对/remoteLogin映射的处理，需要增加一个新流程：

&lt;bean id="handlerMappingB" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt;  
    &lt;property name="mappings"&gt;  
        &lt;props&gt;  
            &lt;prop key="/login"&gt;loginController&lt;/prop&gt;  
            &lt;prop key="/remoteLogin"&gt;remoteController&lt;/prop&gt;  
        &lt;/props&gt;  
    &lt;/property&gt;  
    &lt;property name="interceptors"&gt;  
        &lt;list&gt;  
            &lt;ref bean="localeChangeInterceptor" /&gt;  
        &lt;/list&gt;  
    &lt;/property&gt;  
&lt;/bean&gt;

然后在cas-servlet.xml文件中添加我们上面所配置的remoteController的bean：

&lt;!-- 增加远程控制者，允许以/remote请求启动remote控制流程 --&gt;  
&lt;bean id="remoteLoginController"  
    class="org.springframework.webflow.executor.mvc.FlowController"  
    p:flowExecutor-ref="remoteLoginFlowExecutor"  
    p:defaultFlowId="remoteLogin-webflow"&gt;  
    &lt;property name="argumentHandler"&gt;  
        &lt;bean  
 class="org.springframework.webflow.executor.support.RequestParameterFlowExecutorArgumentHandler"  
            p:flowExecutionKeyArgumentName="lt"  
            p:defaultFlowId="remoteLogin-webflow" /&gt;  
    &lt;/property&gt;  
&lt;/bean&gt;  
&lt;flow:executor id="remoteLoginFlowExecutor" registry-ref="remoteLoginFlowRegistry"&gt;  
    &lt;flow:execution-attributes&gt;  
        &lt;flow:alwaysRedirectOnPause value="false"/&gt;  
    &lt;/flow:execution-attributes&gt;  
&lt;/flow:executor&gt;  
&lt;flow:registry id="remoteLoginFlowRegistry"&gt;  
    &lt;flow:location path="/WEB-INF/remoteLogin-webflow.xml "/&gt;  
&lt;/flow:registry&gt;

可以看到上面将请求指向了webflow配置文件/WEB-INF/remoteLogin-webflow.xml文件，我们需要创建此文件并配置其成为我们所需的流程，以下是remoteLogin-webflow.xml全文：

&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;flow xmlns="[http://www.springframework.org/schema/webflow](http://www.springframework.org/schema/webflow) "  
    xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance) "  
    xsi:schemaLocation="  
              [http://www.springframework.org/schema/webflow](http://www.springframework.org/schema/webflow)  
              [http://www.springframework.org/schema/webflow/spring-webflow-1.0.xsd](http://www.springframework.org/schema/webflow/spring-webflow-1.0.xsd) "&gt;  
    &lt;start-state idref="remoteLogin"/&gt;  
    &lt;!-- 远程登陆主要Action --&gt;  
    &lt;action-state id="remoteLogin"&gt;  
        &lt;action bean="remoteLoginAction" /&gt;  
        &lt;transition on="error" to="remoteCallbackView" /&gt;  
        &lt;transition on="submit" to="bindAndValidate" /&gt;  
        &lt;transition on="checkTicketGrantingTicket" to="ticketGrantingTicketExistsCheck" /&gt;  
    &lt;/action-state&gt;  
    &lt;!-- 远程回调页面，主要以JavaScript的方式回传一些参数用 --&gt;  
    &lt;end-state id="remoteCallbackView" view="remoteCallbackView" /&gt;  
     
    &lt;decision-state id="ticketGrantingTicketExistsCheck"&gt;  
        &lt;if test="${flowScope.ticketGrantingTicketId != null}" then="hasServiceCheck"  
 else="gatewayRequestCheck" /&gt;  
    &lt;/decision-state&gt;  
    &lt;decision-state id="gatewayRequestCheck"&gt;  
        &lt;if test="${externalContext.requestParameterMap\['gateway'] != '' &amp;&amp; externalContext.requestParameterMap\['gateway'] != null &amp;&amp; flowScope.service != null}" then="redirect" else="remoteCallbackView " /&gt;  
    &lt;/decision-state&gt;  
     
    &lt;decision-state id="hasServiceCheck"&gt;  
        &lt;if test="${flowScope.service != null}" then="generateServiceTicket" else="remoteCallbackView " /&gt;  
    &lt;/decision-state&gt;  
     
    &lt;!--  
        The "warn" action makes the determination of whether to redirect directly to the  
 requested  
        service or display the "confirmation" page to go back to the server.  
    --&gt;  
    &lt;decision-state id="warn"&gt;  
        &lt;if test="${flowScope.warnCookieValue}" then="showWarningView" else="redirect" /&gt;  
    &lt;/decision-state&gt;  
    &lt;action-state id="bindAndValidate"&gt;  
        &lt;action bean="authenticationViaFormAction" /&gt;  
        &lt;transition on="success" to="submit" /&gt;  
        &lt;transition on="error" to="remoteCallbackView " /&gt;  
    &lt;/action-state&gt;  
     
    &lt;action-state id="submit"&gt;  
        &lt;action bean="authenticationViaFormAction" method="submit" /&gt;  
        &lt;transition on="warn" to="warn" /&gt;  
        &lt;transition on="success" to="sendTicketGrantingTicket" /&gt;  
        &lt;transition on="error" to="remoteCallbackView " /&gt;  
    &lt;/action-state&gt;  
     
    &lt;action-state id="sendTicketGrantingTicket"&gt;  
        &lt;action bean="sendTicketGrantingTicketAction" /&gt;  
        &lt;transition on="success" to="serviceCheck" /&gt;  
    &lt;/action-state&gt;  
    &lt;decision-state id="serviceCheck"&gt;  
        &lt;if test="${flowScope.service != null}" then="generateServiceTicket"  
 else="remoteCallbackView " /&gt;  
    &lt;/decision-state&gt;  
     
    &lt;action-state id="generateServiceTicket"&gt;  
        &lt;action bean="generateServiceTicketAction" /&gt;  
        &lt;transition on="success" to ="warn" /&gt;  
        &lt;transition on="error" to="remoteCallbackView " /&gt;  
        &lt;transition on="gateway" to="redirect" /&gt;  
    &lt;/action-state&gt;  
    &lt;!--  
        The "showWarningView" end state is the end state for when the user has requested  
 privacy settings (to be "warned") to be turned on.  It delegates to a  
        view defines in default\_views.properties that display the "Please click here to go  
 to the service." message.  
    --&gt;  
    &lt;end-state id="showWarningView" view="casLoginConfirmView" /&gt;  
    &lt;!--  
        The "redirect" end state allows CAS to properly end the workflow while still  
 redirecting  
        the user back to the service required.  
    --&gt;  
    &lt;end-state id="redirect" view="bean:dynamicRedirectViewSelector" /&gt;  
     
    &lt;end-state id="viewServiceErrorView" view="viewServiceErrorView" /&gt;  
     
    &lt;end-state id="viewServiceSsoErrorView" view="viewServiceSsoErrorView" /&gt;  
    &lt;global-transitions&gt;  
        &lt;transition to="viewServiceErrorView" on-  
exception="org.springframework.webflow.execution.repository.NoSuchFlowExecutionException" /  
&gt;  
        &lt;transition to="viewServiceSsoErrorView" on-  
exception="org.jasig.cas.services.UnauthorizedSsoServiceException" /&gt;  
        &lt;transition to="viewServiceErrorView" on-  
exception="org.jasig.cas.services.UnauthorizedServiceException" /&gt;  
    &lt;/global-transitions&gt;  
&lt;/flow&gt;

以上文件根据原login-webflow.xml文件修改，黄色背景为修改部分。可以看到，我们在流程中增加了remoteLogin Action节点和remoteCallback View节点，下面我们配置remoteLogin节点：  
在/WEB-INF/cas-servlet.xml文件中增加remoteLoginAction配置：

&lt;bean id="remoteLoginAction"  
    class="com.baidu.cas.web.flow.RemoteLoginAction "  
    p:argumentExtractors-ref="argumentExtractors"  
    p:warnCookieGenerator-ref="warnCookieGenerator"  
    p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator" /&gt;

同时创建com.baidu.cas.web.flow.RemoteLoginAction类：

/\**  
 * 远程登陆票据提供Action.  
 * 根据InitialFlowSetupAction修改.  
 * 由于InitialFlowSetupAction为final类，因此只能将代码复制过来再进行修改.  
 *  
 * @author GuoLin  
 \*/  
public class RemoteLoginAction extends AbstractAction {  
    /\** CookieGenerator for the Warnings. \*/  
    @NotNull  
    private CookieRetrievingCookieGenerator warnCookieGenerator;  
    /\** CookieGenerator for the TicketGrantingTickets. \*/  
    @NotNull  
    private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;  
    /\** Extractors for finding the service. \*/  
    @NotEmpty  
    private List&lt;ArgumentExtractor&gt; argumentExtractors;  
    /\** Boolean to note whether we've set the values on the generators or not. \*/  
    private boolean pathPopulated = false;  
    protected Event doExecute(final RequestContext context) throws Exception {  
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);  
        if (!this.pathPopulated) {  
            final String contextPath = context.getExternalContext().getContextPath();  
            final String cookiePath = StringUtils.hasText(contextPath) ? contextPath : "/";  
            logger.info("Setting path for cookies to: " + cookiePath);  
            this.warnCookieGenerator.setCookiePath(cookiePath);  
            this.ticketGrantingTicketCookieGenerator.setCookiePath(cookiePath);  
            this.pathPopulated = true;  
        }  
        context.getFlowScope().put("ticketGrantingTicketId",  
                this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));  
        context.getFlowScope().put("warnCookieValue",  
                Boolean.valueOf(this.warnCookieGenerator.retrieveCookieValue(request)));  
        final Service service = WebUtils.getService(this.argumentExtractors, context);  
        if (service != null && logger.isDebugEnabled()) {  
            logger.debug("Placing service in FlowScope: " + service.getId());  
        }  
        context.getFlowScope().put("service", service);  
         
        // 客户端必须传递loginUrl参数过来，否则无法确定登陆目标页面  
        if (StringUtils.hasText(request.getParameter("loginUrl"))) {  
            context.getFlowScope().put("remoteLoginUrl", request.getParameter("loginUrl"));  
        } else {  
            request.setAttribute("remoteLoginMessage", "loginUrl parameter must be supported.");  
            return error();  
        }  
         
        // 若参数包含submit则进行提交，否则进行验证  
        if (StringUtils.hasText(request.getParameter("submit"))) {  
            return result("submit");  
        } else {  
            return result("checkTicketGrantingTicket");  
        }  
    }  
    public void setTicketGrantingTicketCookieGenerator(  
        final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) {  
        this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator;  
    }  
    public void setWarnCookieGenerator(final CookieRetrievingCookieGenerator warnCookieGenerator) {  
        this.warnCookieGenerator = warnCookieGenerator;  
    }  
    public void setArgumentExtractors(  
        final List&lt;ArgumentExtractor&gt; argumentExtractors) {  
        this.argumentExtractors = argumentExtractors;  
    }  
}

以上黄色背景为修改部分，要求客户端必须传入loginUrl参数，且当客户端传入submit参数时，直接为其提交用户名密码  
然后再配置remoteCallbackView显示节点，修改src/default\_views.properties文件，增加remoteCallbackView配置：

\### 配置远程回调页面  
remoteCallbackView.(class)=org.springframework.web.servlet.view.JstlView  
remoteCallbackView.url=/WEB-INF/view/jsp/default/ui/remoteCallbackView.jsp

创建/WEB-INF/view/jsp/default/ui/remoteCallbackView.jsp文件：

&lt;%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%&gt;  
&lt;%@ taglib prefix="c" uri="[http://java.sun.com/jsp/jstl/core"%](http://java.sun.com/jsp/jstl/core%22%) &gt;  
&lt;%@ taglib prefix="spring" uri="[http://www.springframework.org/tags"%](http://www.springframework.org/tags%22%) &gt;  
&lt;html&gt;  
&lt;head&gt;  
    &lt;script type="text/javascript"&gt;  
        var remoteUrl = "${remoteLoginUrl}?validated=true ";  
        // 构造错误消息  
        var errorMessage = "";  
        &lt;spring:hasBindErrors name="credentials"&gt;  
        errorMessage = "&errorMessage=" + encodeURIComponent('&lt;c:forEach  
 var="error" items="${errors.allErrors}"&gt;&lt;spring:message code="${error.code}"  
 text="${error.defaultMessage}" /&gt;&lt;/c:forEach&gt;');  
        &lt;/spring:hasBindErrors&gt;  
         
        // 构造service  
        var serivce = "";  
        &lt;c:if test="${service != null && service != ''}"&gt;  
        service = "&service=" + encodeURIComponent("${service}");  
        &lt;/c:if&gt;  
        // 跳转回去  
        window.location.href = remoteUrl + errorMessage + service;  
    &lt;/script&gt;  
&lt;/head&gt;  
&lt;body&gt;  
    ${remoteLoginMessage}  
&lt;/body&gt;  
&lt;/html&gt;

以上文件注意黄色背景部分validated=true，这里我们与客户端约定，当客户端登陆页面后带有参数validated=true时，不进行票据认证请求。这是因为，客户端登陆页面为[http://clienthost/login.jsp](http://clienthost/) ，那么当用户访问URL  [http://clienthost/login.jsp](http://clienthost/login.jsp) 时， 客户端会重定向到CAS中央服务器请求TGT认证，但认证失败后CAS中央认证服务器会重定向到客户端登陆页面并显示登陆框，此时客户端必须以某种规则避 免重新请求中央认证服务器认证，  在这里我们与客户端约定，当回发的请求为登陆页面且带有参数validated=true时即不转发TGT认证请求，即 http://  
clienthost/login.jsp?validated=true 请求客户端不会重新发送TGT认证请求给中央认证服务器

 

 

[http://fallenlord.blogbus.com/logs/36907044.html](http://fallenlord.blogbus.com/logs/36907044.html)