欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cas 系统实例 服务端配置(二) 自定义登录 博客分类: cas  

程序员文章站 2024-03-13 22:47:58
...

学习一下,自定义登录

在web.xml中增加remoteLogin,例如:

<servlet-mapping>
<servlet-name>cas</servlet-name>
<url-pattern>/myRemoteLogin</url-pattern>
</servlet-mapping>

 在cas-servlet.xml 中增加新的bean并添加相应的映射

<webflow:flow-registry id="flowRegistry" flow-builder-services="builder">
        <webflow:flow-location path="/WEB-INF/login-webflow.xml" id="login" />
        <webflow:flow-location path="/WEB-INF/mylogin-webflow.xml" id="myRemoteLogin" />
    </webflow:flow-registry>
<bean id="remoteLoginAction"
                class="org.jasig.cas.web.my.login.RemoteLoginAction"
            p:argumentExtractors-ref="argumentExtractors"
            p:warnCookieGenerator-ref="warnCookieGenerator"
            p:centralAuthenticationService-ref="centralAuthenticationService"
            p:initialFlowSetupAction-ref="initialFlowSetupAction"
            p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator"
            />
<bean id="generateResponse" class="org.jasig.cas.web.my.login.GenerateResponse"></bean>
 

mylogin-webflow.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/webflow
                          http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

	
    <!-- 开始 -->
    <on-start>
    	<!-- 定义执行方法  到数据库相关验证 -->
        <evaluate expression="remoteLoginAction" />
    </on-start>
    
    <!-- 判断是否有错误 -->
    <decision-state id="hasError">
		<if test="flowScope.error neq null  &amp;&amp; flowScope.error neq '' " then="hasfailPageCheck" else="sendTicketGrantingTicket" />
	</decision-state>
	<!-- 取得错误信息,及返回页面 -->
	<action-state id="hasfailPageCheck">
        <evaluate 
        expression="generateResponse.getResponse( flowRequestContext,true)" 
        result-type="org.jasig.cas.authentication.principal.Response" 
        result="flowScope.response" />
        <transition to="postView" />
    </action-state> 
	<action-state id="sendTicketGrantingTicket">
        <evaluate expression="sendTicketGrantingTicketAction" />
		<transition to="serviceCheck" />
	</action-state>
	<decision-state id="serviceCheck">
		<if test="flowScope.service neq null" then="generateServiceTicket" else="viewGenericLoginSuccess" />
	</decision-state>
	
	
	<!-- 产生service票据 -->
	<action-state id="generateServiceTicket">
        <evaluate expression="generateServiceTicketAction" />
		<transition on="success" to ="getReturnResponse" /> 
		<transition on="gateway" to="hasError" />
	</action-state>
	
	
	<!-- 取得正常返回,及返回页面 -->
	<action-state id="getReturnResponse">
        <evaluate 
        expression="generateResponse.getResponse( flowRequestContext,false)" 
        result-type="org.jasig.cas.authentication.principal.Response" 
        result="flowScope.response" />
        <transition to="redirectView" />
    </action-state>
	
	<end-state id="postView" view="postResponseView">
        <on-entry>
            <set name="requestScope.parameters" value="flowScope.response.attributes" />
            <set name="requestScope.originalUrl" value="flowScope.response.url" />
        </on-entry>
    </end-state>
    <end-state id="viewGenericLoginSuccess" view="casLoginGenericSuccessView" />
    <end-state id="redirectView" view="externalRedirect:http://localhost:8081/casclient4/sso/index.jsp" />
    
    <global-transitions>
		<transition to="viewServiceErrorView" on-exception="org.springframework.webflow.execution.repository.NoSuchFlowExecutionException" />
        <transition to="viewServiceSsoErrorView" on-exception="org.jasig.cas.services.UnauthorizedSsoServiceException" />
		<transition to="viewServiceErrorView" on-exception="org.jasig.cas.services.UnauthorizedServiceException" />
	</global-transitions>

	
</flow>

 RemoteLoginAction.java

package org.jasig.cas.web.my.login;

import java.util.List;

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

import org.hibernate.validator.constraints.NotEmpty;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.web.flow.InitialFlowSetupAction;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.util.StringUtils;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

/**
* 远程登陆票据提供Action.
* 根据InitialFlowSetupAction修改.
* 由于InitialFlowSetupAction为final类,因此只能将代码复制过来再进行修改.
* 
* @author GuoLin
*/
public class RemoteLoginAction extends AbstractAction {
    /** CookieGenerator for the Warnings. */
    @NotNull
    private CookieRetrievingCookieGenerator warnCookieGenerator;
   
    /** Extractors for finding the service. */
    @NotEmpty
    private List<ArgumentExtractor> argumentExtractors;
     
    
    /** Core we delegate to for handling all ticket related tasks. */
    @NotNull
    private CentralAuthenticationService centralAuthenticationService;
    
 	@NotNull
    private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;
    
    private InitialFlowSetupAction initialFlowSetupAction;
    
    protected Event doExecute(final RequestContext context)   {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    	
        /***
         * 必须的
         */
        context.getFlowScope().put( "warnCookieValue", Boolean.valueOf(this.warnCookieGenerator.retrieveCookieValue(request)));
        
        
    	String uName = request.getParameter("username");
    	String password = request.getParameter("password");
    	
    	
    	Credentials credentials =new UsernamePasswordCredentials(uName,password);
    	if (!this.initialFlowSetupAction.pathPopulated) {
            final String contextPath = request.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.initialFlowSetupAction.pathPopulated = true;
        }
    	
    	context.getFlowScope().put("credentials", credentials);
    	
    	 
    	String createTicketGrantingTicket;
		try {
			createTicketGrantingTicket = this.centralAuthenticationService.createTicketGrantingTicket(credentials);
			/***
			 * 必须的
			 */
			 WebUtils.putTicketGrantingTicketInRequestScope(context,createTicketGrantingTicket );
		} catch (TicketException e) {
			context.getFlowScope().put("error", "error.userOrPassword.error");
			e.printStackTrace();
		}
    	 
        // putWarnCookieIfRequestParameterPresent(context);
         
         
         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);
    	
        return result("submit");
    }
    
    public void setWarnCookieGenerator(final CookieRetrievingCookieGenerator warnCookieGenerator) {
        this.warnCookieGenerator = warnCookieGenerator;
    }
    public void setArgumentExtractors(
        final List<ArgumentExtractor> argumentExtractors) {
        this.argumentExtractors = argumentExtractors;
    }
    public final void setCentralAuthenticationService(final CentralAuthenticationService centralAuthenticationService) {
        this.centralAuthenticationService = centralAuthenticationService;
    }
    
	public void setInitialFlowSetupAction(
			InitialFlowSetupAction initialFlowSetupAction) {
		this.initialFlowSetupAction = initialFlowSetupAction;
	}
	 public void setTicketGrantingTicketCookieGenerator(
	            final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) {
	            this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator;
	        }
    
}

 GenerateResponse.java

package org.jasig.cas.web.my.login;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jasig.cas.authentication.principal.Response;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.webflow.execution.RequestContext;

public class GenerateResponse {
	 public Response getResponse( final RequestContext context,boolean haveError) {
		 	String orgUrl = "";

		 	final Map<String, String> parameters = new HashMap<String, String>();
		 	
		 	
	        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
	        if(haveError)
	        {
	        	orgUrl =request.getParameter("failpae");
	        	String error = (String) context.getFlowScope().get("error");
	        	parameters.put("error", error);
	        	parameters.put("result", "false");
	        }else
	        {
	        	orgUrl =request.getParameter("service");
	        	parameters.put("result", "true");
	        }
	        context.getFlowScope().put("responseUrl", orgUrl);
 
	        Response ret =  Response.getRedirectResponse(orgUrl, parameters);
	        
	        return ret;
	    }

}

 客户端端方法:

<form id="myLoginForm" action="http://localhost:8081/casserver/myRemoteLogin" method="post">
            <input type="hidden" id="targetService" name="service" value="http://localhost:8081/casclient4/sso/index.jsp">
            <input type="hidden" name="failpae" value="http://localhost:8081/casclient4/index.jsp">

 
            <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>验证码</td>
                <td><input type="text" /><img
									src="http://localhost:8081/casserver/random"
									class="sign_img fl mt5"  /></td></tr>
                <tr>
                    <td colspan="2"><input type="submit" value="登陆" /></td>
                </tr>
                
            </table>
        </form>