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