`
waw
  • 浏览: 23583 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

CAS Server 3.5.1 之自定义登录页

阅读更多
参考http://denger.iteye.com/blog/809170
参考https://wiki.jasig.org/display/CAS/Using+CAS+without+the+Login+Screen
做如下修改
1.修改ProvideLoginTicketAction类 增加 lt 参数
2.CAS的XML配置文件 cas-servlet.xml
3.修改跳转页面 viewRedirectToRequestor.jsp
4.web-flow.xml修改
5.修改AuthenticationViaFormAction类,可以修改源码,也可以Spring进cas-servlet.xml ,修改位置见下面代码
6.default_views.properties修改





<bean id="provideLoginTicketAction" class="com.woniu.cas.ProvideLoginTicketAction"
   p:ticketIdGenerator-ref="loginTicketUniqueIdGenerator"/>


package com.woniu.cas;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.util.UniqueTicketIdGenerator;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

/**
 * 
 * 
 * 
 */
public class ProvideLoginTicketAction extends AbstractAction{
	
	/** 3.5.1 - Login tickets SHOULD begin with characters "LT-" */
    private static final String PREFIX = "LT";

    /** Logger instance */
    private final Log logger = LogFactory.getLog(getClass());


    @NotNull
    private UniqueTicketIdGenerator ticketIdGenerator;

    public final String generate(final RequestContext context) {
        final String loginTicket = this.ticketIdGenerator.getNewTicketId(PREFIX);
        this.logger.debug("Generated login ticket " + loginTicket);
        WebUtils.putLoginTicket(context, loginTicket);
        return "generated";
    }

    public void setTicketIdGenerator(final UniqueTicketIdGenerator generator) {
        this.ticketIdGenerator = generator;
    }
	@Override
	protected Event doExecute(RequestContext context) throws Exception {
		
		final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
		
		if (request.getParameter("get-lt") != null && request.getParameter("get-lt").equalsIgnoreCase("true")) {
			
			final String loginTicket = this.ticketIdGenerator.getNewTicketId(PREFIX);
	        this.logger.debug("Generated login ticket " + loginTicket);
	        WebUtils.putLoginTicket(context, loginTicket);
			
			return result("loginTicketRequested");
		}
		return result("continue");
	}
	
}









<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="com.woniu.cas.CasUtility"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%
	String separator = "";
        // 需要输入 login-at 参数,当生成lt后或登录失败后则重新跳转至 原登录页,并传入参数 lt 和 error_message
	String referer = request.getParameter("login-at");

	referer = CasUtility.resetUrl(referer);
	if (referer != null && referer.length() > 0) {
		separator = (referer.indexOf("?") > -1) ? "&" : "?";
%>
<html>
	<title>cas get login ticket</title>
	<head>
		<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<script>
		var redirectURL = "<%=referer + separator%>lt=${loginTicket}&execution=${flowExecutionKey}";
		alert(redirectURL);
		<spring:hasBindErrors name="credentials">
			var errorMsg = '<c:forEach var="error" items="${errors.allErrors}"><spring:message code="${error.code}" text="${error.defaultMessage}" /></c:forEach>';
            redirectURL += '&error_message=' + encodeURIComponent (errorMsg);
        </spring:hasBindErrors>
         window.location.href = redirectURL;
       </script>
	</head>
	<body></body>
</html>
<%
	} else {
%>		
		<script>window.location.href = "/member/login";</script>
<%		
	}
%>



增加自定义的跳转页面

<action-state id="provideLoginTicket">
        <evaluate expression="provideLoginTicketAction"/>  
        <transition on="loginTicketRequested" to ="viewRedirectToRequestor" />  
        <transition on="continue" to="ticketGrantingTicketExistsCheck" />  
    </action-state>
    
    <view-state id="viewRedirectToRequestor" view="casRedirectToRequestorView" model="credentials">  
        <binder>  
            <binding property="username" />  
            <binding property="password" />  
        </binder>  
        <on-entry>  
            <set name="viewScope.commandName" value="'credentials'" />  
        </on-entry>  
        <transition on="submit" bind="true" validate="true" to="realSubmit">  
            <set name="flowScope.credentials" value="credentials" />  
            <evaluate expression="authenticationViaFormAction.doBind(flowRequestContext, flowScope.credentials)" />  
        </transition>  
    </view-state>  




修改增加 <transition on="errorForRemoteRequestor" to="viewRedirectToRequestor" /> 
<action-state id="realSubmit">
        <evaluate expression="authenticationViaFormAction.submit(flowRequestContext, flowScope.credentials, messageContext)" />
        <!--
	      To enable LPPE on the 'warn' replace the below transition with:
	      <transition on="warn" to="passwordPolicyCheck" />

	      CAS will attempt to transition to the 'warn' when there's a 'renew' parameter
	      and there exists a ticketGrantingId and a service for the incoming request.
	    -->
		<transition on="warn" to="warn" />
		<!--
	      To enable LPPE on the 'success' replace the below transition with:
	      <transition on="success" to="passwordPolicyCheck" />
	    -->
		<transition on="success" to="sendTicketGrantingTicket" />
		<transition on="error" to="generateLoginTicket" />
		<transition on="errorForRemoteRequestor" to="viewRedirectToRequestor" />  
		<transition on="accountDisabled" to="casAccountDisabledView" />
	    <transition on="mustChangePassword" to="casMustChangePassView" />
	    <transition on="accountLocked" to="casAccountLockedView" />
	    <transition on="badHours" to="casBadHoursView" />
	    <transition on="badWorkstation" to="casBadWorkstationView" />
	    <transition on="passwordExpired" to="casExpiredPassView" />
	</action-state>




package com.woniu.cas;
/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License.  You may obtain a
 * copy of the License at the following location:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.web.bind.CredentialsBinder;
import org.jasig.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.util.StringUtils;
import org.springframework.web.util.CookieGenerator;
import org.springframework.webflow.execution.RequestContext;

/**
 * Action to authenticate credentials and retrieve a TicketGrantingTicket for
 * those credentials. If there is a request for renew, then it also generates
 * the Service Ticket required.
 * 
 * @author Scott Battaglia
 * @version $Revision$ $Date$
 * @since 3.0.4
 */
public class AuthenticationViaFormAction {

    /**
     * Binder that allows additional binding of form object beyond Spring
     * defaults.
     */
    private CredentialsBinder credentialsBinder;

    /** Core we delegate to for handling all ticket related tasks. */
    @NotNull
    private CentralAuthenticationService centralAuthenticationService;

    @NotNull
    private CookieGenerator warnCookieGenerator;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    public final void doBind(final RequestContext context, final Credentials credentials) throws Exception {
    	
    	final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

        if (this.credentialsBinder != null && this.credentialsBinder.supports(credentials.getClass())) {
            this.credentialsBinder.bind(request, credentials);
        }
    }
    
    public final String submit(final RequestContext context, final Credentials credentials, final MessageContext messageContext) throws Exception {
        // Validate login ticket
    	final String authoritativeLoginTicket = WebUtils.getLoginTicketFromFlowScope(context);
        final String providedLoginTicket = WebUtils.getLoginTicketFromRequest(context);
        
        System.out.println(authoritativeLoginTicket+","+providedLoginTicket);
        if (!authoritativeLoginTicket.equals(providedLoginTicket)) {
        	System.out.println("providedLoginTicket ERROR");
            this.logger.warn("Invalid login ticket " + providedLoginTicket);
            final String code = "INVALID_TICKET";
            messageContext.addMessage(
                new MessageBuilder().error().code(code).arg(providedLoginTicket).defaultText(code).build());
            return "error";
        }
        
        final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
        final Service service = WebUtils.getService(context);
        if (StringUtils.hasText(context.getRequestParameters().get("renew")) && ticketGrantingTicketId != null && service != null) {

            try {
                final String serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, credentials);
                WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
                putWarnCookieIfRequestParameterPresent(context);
                return "warn";
            } catch (final TicketException e) {
                if (isCauseAuthenticationException(e)) {
                    populateErrorsInstance(e, messageContext);
                    return getAuthenticationExceptionEventId(e);
                }
                
                this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId);
                if (logger.isDebugEnabled()) {
                    logger.debug("Attempted to generate a ServiceTicket using renew=true with different credentials", e);
                }
            }
        }

        try {
            WebUtils.putTicketGrantingTicketInRequestScope(context, this.centralAuthenticationService.createTicketGrantingTicket(credentials));
            putWarnCookieIfRequestParameterPresent(context);
            return "success";
        } catch (final TicketException e) {
            populateErrorsInstance(e, messageContext);
            
            String referer = context.getRequestParameters().get("login-at");  
            if (!org.apache.commons.lang.StringUtils.isBlank(referer)) {  
            	System.out.println("errorForRemoteRequestor!!!!!!!!!!!!!!!!!!!");
            	return "errorForRemoteRequestor";  
            } 
            return "error"; 
            
//            if (isCauseAuthenticationException(e))
//                return getAuthenticationExceptionEventId(e);
//            return "error";
        }
    }


    private void populateErrorsInstance(final TicketException e, final MessageContext messageContext) {
    	System.out.println("populateErrorsInstance");
        try {
            messageContext.addMessage(new MessageBuilder().error().code(e.getCode()).defaultText(e.getCode()).build());
        } catch (final Exception fe) {
            logger.error(fe.getMessage(), fe);
        }
    }

    private void putWarnCookieIfRequestParameterPresent(final RequestContext context) {
    	System.out.println("putWarnCookieIfRequestParameterPresent");
    	final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

        if (StringUtils.hasText(context.getExternalContext().getRequestParameterMap().get("warn"))) {
            this.warnCookieGenerator.addCookie(response, "true");
        } else {
            this.warnCookieGenerator.removeCookie(response);
        }
    }
    
    private AuthenticationException getAuthenticationExceptionAsCause(final TicketException e) {
        return (AuthenticationException) e.getCause();
    }

    private String getAuthenticationExceptionEventId(final TicketException e) {
        final AuthenticationException authEx = getAuthenticationExceptionAsCause(e);

        if (this.logger.isDebugEnabled())
            this.logger.debug("An authentication error has occurred. Returning the event id " + authEx.getType());

        return authEx.getType();
    }

    private boolean isCauseAuthenticationException(final TicketException e) {
        return e.getCause() != null && AuthenticationException.class.isAssignableFrom(e.getCause().getClass());
    }

    public final void setCentralAuthenticationService(final CentralAuthenticationService centralAuthenticationService) {
        this.centralAuthenticationService = centralAuthenticationService;
    }

    /**
     * Set a CredentialsBinder for additional binding of the HttpServletRequest
     * to the Credentials instance, beyond our default binding of the
     * Credentials as a Form Object in Spring WebMVC parlance. By the time we
     * invoke this CredentialsBinder, we have already engaged in default binding
     * such that for each HttpServletRequest parameter, if there was a JavaBean
     * property of the Credentials implementation of the same name, we have set
     * that property to be the value of the corresponding request parameter.
     * This CredentialsBinder plugin point exists to allow consideration of
     * things other than HttpServletRequest parameters in populating the
     * Credentials (or more sophisticated consideration of the
     * HttpServletRequest parameters).
     *
     * @param credentialsBinder the credentials binder to set.
     */
    public final void setCredentialsBinder(final CredentialsBinder credentialsBinder) {
        this.credentialsBinder = credentialsBinder;
    }
    
    public final void setWarnCookieGenerator(final CookieGenerator warnCookieGenerator) {
        this.warnCookieGenerator = warnCookieGenerator;
    }
}




<bean id="authenticationViaFormAction" class=" com.woniu.cas.AuthenticationViaFormAction"
        p:centralAuthenticationService-ref="centralAuthenticationService"
        p:warnCookieGenerator-ref="warnCookieGenerator"/>



工具类:

package com.woniu.cas;

public class CasUtility {

	/**
	 * Removes the previously attached GET parameters "lt" and "error_message"
	 * to be able to send new ones.
	 * 
	 * @param casUrl
	 * @return
	 */
	public static String resetUrl(String casUrl) {
		String cleanedUrl;
		String[] paramsToBeRemoved = new String[] { "lt", "error_message", "get-lt" };
		cleanedUrl = removeHttpGetParameters(casUrl, paramsToBeRemoved);
		return cleanedUrl;
	}

	/**
	 * Removes selected HTTP GET parameters from a given URL
	 * 
	 * @param casUrl
	 * @param paramsToBeRemoved
	 * @return
	 */
	public static String removeHttpGetParameters(String casUrl,
			String[] paramsToBeRemoved) {
		String cleanedUrl = casUrl;
		if (casUrl != null) {
			// check if there is any query string at all
			if (casUrl.indexOf("?") == -1) {
				return casUrl;
			} else {
				// determine the start and end position of the parameters to be
				// removed
				int startPosition, endPosition;
				boolean containsOneOfTheUnwantedParams = false;
				for (String paramToBeErased : paramsToBeRemoved) {
					startPosition = -1;
					endPosition = -1;
					if (cleanedUrl.indexOf("?" + paramToBeErased + "=") > -1) {
						startPosition = cleanedUrl.indexOf("?"
								+ paramToBeErased + "=") + 1;
					} else if (cleanedUrl.indexOf("&" + paramToBeErased + "=") > -1) {
						startPosition = cleanedUrl.indexOf("&"
								+ paramToBeErased + "=") + 1;
					}
					if (startPosition > -1) {
						int temp = cleanedUrl.indexOf("&", startPosition);
						endPosition = (temp > -1) ? temp + 1 : cleanedUrl
								.length();
						// remove that parameter, leaving the rest untouched
						cleanedUrl = cleanedUrl.substring(0, startPosition)
								+ cleanedUrl.substring(endPosition);
						containsOneOfTheUnwantedParams = true;
					}
				}

				// wenn nur noch das Fragezeichen vom query string übrig oder am
				// schluss ein "&", dann auch dieses entfernen
				if (cleanedUrl.endsWith("?") || cleanedUrl.endsWith("&")) {
					cleanedUrl = cleanedUrl.substring(0,
							cleanedUrl.length() - 1);
				}
				// parameter mehrfach angegeben wurde...
				if (!containsOneOfTheUnwantedParams)
					return casUrl;
				else
					cleanedUrl = removeHttpGetParameters(cleanedUrl,
							paramsToBeRemoved);
			}
		}
		return cleanedUrl;
	}
}




6.default_views.properties修改
### Redirect with login ticket view
casRedirectToRequestorView.(class)=org.springframework.web.servlet.view.JstlView
casRedirectToRequestorView.url=/WEB-INF/view/jsp/default/ui/viewRedirectToRequestor.jsp
分享到:
评论
5 楼 sanyaocun000 2013-11-18  
你好,按照您的做法,到时可以的会转到客户端的登录界面,可为什么点击登录后跳转到认证服务器的登录页面呢?
4 楼 sunrui0451 2013-10-21  
为什么按你配置的会,跳到cas页的login页里呢?
3 楼 afeifqh 2013-09-27  
我的也可以获取lt。但是服务端发布到服务器上cas用https方式的时候,获取到lt,点击登录就跳转到了cas的默认登陆页去了。 但是在我本地开启as服务端却可以(本地采用http)。
不支持服务器用https方式么?
2 楼 fangxia123 2013-03-15  
你好,我按照您说的做了,后台数据get-lt::::true都可以获取到,lt也有值,可是在点登录按钮后却是跳转到cas的登录页面去了,这是为什么???
1 楼 fangxia123 2013-03-15  
你好,我按照您说的做了,后台数据get-lt::::true都可以获取到,lt也有值,可是在点登录按钮后却是跳转到cas的登录页面去了,这是为什么???

相关推荐

    cas-server-3.5.1-release.zip

    这个"cas-server-3.5.1-release.zip"文件包含了CAS服务器3.5.1版本的源码、文档和其他相关资源,允许开发者进行定制化部署和扩展。 在CAS 3.5.1版本中,主要关注以下几个关键知识点: 1. **单一登录机制**:CAS的...

    cas-server-3.5.1和cas-client-3.2.1

    首先,我们来看`cas-server-3.5.1`部分。这是CAS服务器端的核心组件,负责处理用户的认证请求和响应。3.5.1版本可能包含以下关键模块: 1. **Web应用程序**:基于Servlet的Web应用,运行在Tomcat、Jetty等Servlet...

    cas-client-core-3.5.1.jar

    CAS Client 3.5.1客户端,用于单点登录客户端拦截,编译环境JDK1.8,可用于JDK1.8及以上Java版本。

    mybatis-plus3.5.1,代码生成器集成(自定义模板).pdf

    ### MyBatis-Plus 3.5.1 代码生成器集成(自定义模板)详解 #### 一、概述 MyBatis-Plus (MP) 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。在实际开发过程中,...

    cas-server-3.5.2.1-release.zip

    综上所述,"cas-server-3.5.2.1-release.zip" 包含了实现单点登录服务所需的所有组件和配置,是构建和管理企业级SSO解决方案的关键。解压并部署这个包后,你可以根据组织需求进行定制和配置,实现跨应用的统一身份...

    android Zxing扫描二维码条形码功能仿微信自定义扫码框扫描线边框样式Eclipse版本

    在本项目中,我们将讨论如何在Eclipse环境下,使用Zxing库实现类似微信的自定义扫码框和扫描线边框样式。 首先,我们需要在项目中引入Zxing库。由于这是Eclipse版本,你需要将Zxing的源代码导入到你的工程中,或者...

    CAS安装指南以及开发步骤 V1.0.docx

    当需要登录时,CASClient会将请求重定向至CASServer进行身份验证。 #### CAS的安装与配置 ##### 1. 服务端下载与配置 服务端的下载地址为:[http://downloads.jasig.org/cas/cas-server-3.5.1-release.zip]...

    cas-client3.5单点登录官方客户端程序demo

    在这个"cas-client3.5单点登录官方客户端程序demo"中,我们可以深入理解如何在Java环境中集成CAS客户端来实现单点登录功能。 首先,CAS客户端3.5是为Java应用程序设计的,它允许这些应用与CAS服务器进行通信,验证...

    selenium 3.5.1

    selenium-server-3.5.1.zip selenium-server-standalone-3.5.1.jar IEDriverServer_Win32_3.5.1.zip IEDriverServer_x64_3.5.1.zip chromedriver_linux32.zip chromedriver_linux64.zip chromedriver_mac32....

    jquery-3.5.1.rar

    《jQuery 3.5.1:前端开发的强大工具》 jQuery,这个小巧而强大的JavaScript库,自2006年发布以来,一直是前端开发者的重要工具。本次提供的“jquery-3.5.1.rar”文件,包含了jQuery的核心库版本3.5.1,这是对这个...

    Exchange Server 2010 安装及CAS服务器配置

    ### Exchange Server 2010 安装及CAS服务器配置 #### 一、Exchange Server 2010 安装前的准备工作 在正式安装Exchange Server 2010之前,需要确保网络环境符合一定的标准,并对现有环境进行充分评估。 1. **评估...

    jquery 3.5.1

    在本篇文章中,我们将深入探讨jQuery 3.5.1的核心特性、优势以及如何在项目中有效地使用这两个JavaScript文件:`jquery-3.5.1.js`和`jquery-3.5.1.min.js`。 一、jQuery简介 jQuery是由John Resig于2006年创建的,...

    protobuf 3.5.1

    protocolbuffer(以下简称PB)是google 的一种数据交换的格式,它独立于语言,独立于平台。...由于它是一种二进制的格式,比使用 xml 进行数据交换快许多。可以把它用于分布式应用之间的数据通信...protoc-3.5.1-win32.zip

    jQuery-3.5.1压缩版

    jQuery-3.5.1压缩版

    jquery-3.5.1.min.js_jquery-3.5.1.min.js_jquery_

    《jQuery 3.5.1:JavaScript开发者的得力助手》 jQuery,作为一款广泛使用的JavaScript库,一直以来都是Web开发者的首选工具。标题中的“jquery-3.5.1.min.js”代表的是jQuery库的3.5.1版本的压缩后的最小化文件,...

    Ice-3.5.1.zip

    《Ice-3.5.1源码解析与深入理解》 Ice是一款强大的分布式对象中间件,它由ZeroC公司开发,旨在提供一种高效、安全、跨语言的通信机制。Ice-3.5.1是其在201X年发布的一个稳定版本,包含了丰富的功能和改进,对于学习...

    jquery-3.5.1.zip

    《jQuery 3.5.1:前端开发的强大工具》 jQuery,这个JavaScript库,自2006年发布以来,一直是前端开发领域的明星工具。它以其简洁的API、丰富的功能和广泛的浏览器兼容性赢得了开发者们的青睐。本次我们将深入探讨...

    jquery-3.5.1.min.js

    jquery3.5.1版本

    Editplus-3.5.1序列号

    它还支持自定义的代码模板,用户可以根据自己的需求创建和保存常用代码结构,方便日后重复使用。 对于网页开发者,EditPlus提供了FTP(文件传输协议)功能,可以直接在编辑器内上传和下载文件到远程服务器,无需...

Global site tag (gtag.js) - Google Analytics