CAS SSO改造步骤(3)

  1. 上面写完了登录验证。那么接下来还有几个部分需要修改。  
  2. 上面写完了登录验证。那么接下来还有几个部分需要修改。
  3. 当用户登录成功之后从应用1跳转到应用2的时候也需要增加一个判断应用2是否授权的操作。具体是在GenerateServiceTicketAction.java类中。
  4. 当用户退出的时候(包括浏览器退出都要触发LogoutController.java类中的操作)因此退出的时候一定要更改用户的登录状态,负责下一次用户将无法登录。
  5. 其他的如果你有其他的地方需要改造,那么不管是login-webflow.xml,还是cas-servlet.xml.都可以相应的更改。

将核心代码展示如下:

GenerateServiceTicketAction.Java

  1. /* 
  2.  * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license 
  3.  * distributed with this file and available online at 
  4.  * http://www.ja-sig.org/products/cas/overview/license/ 
  5.  */  
  6. package org.jasig.cas.web.flow;  
  7.   
  8. import java.net.MalformedURLException;  
  9. import java.net.URL;  
  10. import java.util.regex.Matcher;  
  11. import java.util.regex.Pattern;  
  12.   
  13. import org.apache.commons.logging.LogFactory;  
  14. import org.jasig.cas.CentralAuthenticationService;  
  15. import org.jasig.cas.authentication.principal.Credentials;  
  16. import org.jasig.cas.authentication.principal.Service;  
  17. import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;  
  18. import org.jasig.cas.ticket.TicketException;  
  19. import org.jasig.cas.web.support.WebUtils;  
  20. import org.jasig.services.persondir.support.jdbc.ApplicationAuthoritiedAuthenticationDAO;  
  21. import org.slf4j.Logger;  
  22. import org.slf4j.LoggerFactory;  
  23. import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;  
  24. import org.springframework.util.Assert;  
  25. import org.springframework.util.StringUtils;  
  26. import org.springframework.webflow.action.AbstractAction;  
  27. import org.springframework.webflow.execution.Event;  
  28. import org.springframework.webflow.execution.RequestContext;  
  29.   
  30. import javax.servlet.http.HttpServletRequest;  
  31. import javax.sql.DataSource;  
  32. import javax.validation.constraints.NotNull;  
  33.   
  34. /** 
  35.  * Action to generate a service ticket for a given Ticket Granting Ticket and 
  36.  * Service. 
  37.  *  
  38.  * @author Scott Battaglia 
  39.  * @version $Revision$ $Date$ 
  40.  * @since 3.0.4 
  41.  */  
  42. public final class GenerateServiceTicketAction extends AbstractAction {  
  43.      
  44.     private final Logger log = LoggerFactory.getLogger(this.getClass());  
  45.     /** Instance of CentralAuthenticationService. */  
  46.     @NotNull  
  47.     private CentralAuthenticationService centralAuthenticationService;  
  48.   
  49.     /** Instance of ApplicationAuthoritiedAuthenticationDAO. */  
  50.     @NotNull  
  51.     <span style="color:#000099;">private ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO;  
  52.       
  53. </span>    /** check the url your are request is valid or not*/  
  54.    <span style="color:#ff0000;"protected boolean checkUrl(final RequestContext context){  
  55.         UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials)this.centralAuthenticationService.getCredentials();  
  56.         HttpServletRequest request = WebUtils.getHttpServletRequest(context);  
  57.         String url = request.getParameter("service").toString();  
  58.         Assert.notNull(userinfo,"userinfo is null");  
  59.         Assert.notNull(url,"url is null");  
  60.           
  61.         boolean result = this.applicationAuthoritiedAuthenticationDAO.CheckApplicationURLIsAuthority(url, userinfo.getUsername());  
  62.         if(result){  
  63.             log.error("Your have no authoriation to log this application");  
  64.             return false;  
  65.         }  
  66.         log.info("the Url is valid\n");  
  67.         return true;  
  68.     }  
  69. </span>    protected Event doExecute(final RequestContext context) {  
  70.           
  71.         <span style="color:#ff0000;">boolean result = checkUrl(context);  
  72.         if(!result){  
  73.             return error();  
  74.         }  
  75. </span>        final Service service = WebUtils.getService(context);  
  76.         final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);  
  77.   
  78.         try {  
  79.             final String serviceTicketId = this.centralAuthenticationService  
  80.                 .grantServiceTicket(ticketGrantingTicket,  
  81.                     service);  
  82.             WebUtils.putServiceTicketInRequestScope(context,  
  83.                 serviceTicketId);  
  84.             return success();  
  85.         } catch (final TicketException e) {  
  86.             if (isGatewayPresent(context)) {  
  87.                 return result("gateway");  
  88.             }  
  89.         }  
  90.   
  91.         return error();  
  92.     }  
  93.   
  94.     public void setCentralAuthenticationService(  
  95.         final CentralAuthenticationService centralAuthenticationService) {  
  96.         this.centralAuthenticationService = centralAuthenticationService;  
  97.     }  
  98.   
  99.     protected boolean isGatewayPresent(final RequestContext context) {  
  100.         return StringUtils.hasText(context.getExternalContext()  
  101.             .getRequestParameterMap().get("gateway"));  
  102.     }  
  103.       
  104.     public void setApplicationAuthoritiedAuthenticationDAO(  
  105.             ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO) {  
  106.         this.applicationAuthoritiedAuthenticationDAO = applicationAuthoritiedAuthenticationDAO;  
  107.     }  
  108.     public ApplicationAuthoritiedAuthenticationDAO getApplicationAuthoritiedAuthenticationDAO() {  
  109.         return applicationAuthoritiedAuthenticationDAO;  
  110.     }  
  111. }  
/*
 * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
 * distributed with this file and available online at
 * http://www.ja-sig.org/products/cas/overview/license/
 */
package org.jasig.cas.web.flow;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.LogFactory;
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.support.WebUtils;
import org.jasig.services.persondir.support.jdbc.ApplicationAuthoritiedAuthenticationDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

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

/**
 * Action to generate a service ticket for a given Ticket Granting Ticket and
 * Service.
 * 
 * @author Scott Battaglia
 * @version $Revision$ $Date$
 * @since 3.0.4
 */
public final class GenerateServiceTicketAction extends AbstractAction {
   
	private final Logger log = LoggerFactory.getLogger(this.getClass());
    /** Instance of CentralAuthenticationService. */
    @NotNull
    private CentralAuthenticationService centralAuthenticationService;

    /** Instance of ApplicationAuthoritiedAuthenticationDAO. */
    @NotNull
    private ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO;
    
    /** check the url your are request is valid or not*/
    protected boolean checkUrl(final RequestContext context){
    	UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials)this.centralAuthenticationService.getCredentials();
    	HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    	String url = request.getParameter("service").toString();
    	Assert.notNull(userinfo,"userinfo is null");
    	Assert.notNull(url,"url is null");
    	
		boolean result = this.applicationAuthoritiedAuthenticationDAO.CheckApplicationURLIsAuthority(url, userinfo.getUsername());
    	if(result){
    		log.error("Your have no authoriation to log this application");
    		return false;
    	}
		log.info("the Url is valid\n");
		return true;
    }
    protected Event doExecute(final RequestContext context) {
    	
    	boolean result = checkUrl(context);
    	if(!result){
    		return error();
    	}
        final Service service = WebUtils.getService(context);
        final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);

        try {
            final String serviceTicketId = this.centralAuthenticationService
                .grantServiceTicket(ticketGrantingTicket,
                    service);
            WebUtils.putServiceTicketInRequestScope(context,
                serviceTicketId);
            return success();
        } catch (final TicketException e) {
            if (isGatewayPresent(context)) {
                return result("gateway");
            }
        }

        return error();
    }

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

    protected boolean isGatewayPresent(final RequestContext context) {
        return StringUtils.hasText(context.getExternalContext()
            .getRequestParameterMap().get("gateway"));
    }
	
	public void setApplicationAuthoritiedAuthenticationDAO(
			ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO) {
		this.applicationAuthoritiedAuthenticationDAO = applicationAuthoritiedAuthenticationDAO;
	}
	public ApplicationAuthoritiedAuthenticationDAO getApplicationAuthoritiedAuthenticationDAO() {
		return applicationAuthoritiedAuthenticationDAO;
	}
}


LogoutController.java

  1. /* 
  2.  * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license 
  3.  * distributed with this file and available online at 
  4.  * http://www.ja-sig.org/products/cas/overview/license/ 
  5.  */  
  6. package org.jasig.cas.web;  
  7.   
  8. import java.util.Map;  
  9.   
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12. import javax.sql.DataSource;  
  13. import javax.validation.constraints.NotNull;  
  14.   
  15. import org.jasig.cas.CentralAuthenticationService;  
  16. import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;  
  17. import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;  
  18. import org.jasig.services.persondir.support.jdbc.ModifyLoginedStatusAttributeDAO;  
  19. import org.springframework.jdbc.core.JdbcTemplate;  
  20. import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;  
  21. import org.springframework.util.Assert;  
  22. import org.springframework.web.servlet.ModelAndView;  
  23. import org.springframework.web.servlet.mvc.AbstractController;  
  24. import org.springframework.web.servlet.view.RedirectView;  
  25.   
  26. /** 
  27.  * Controller to delete ticket granting ticket cookie in order to log out of 
  28.  * single sign on. This controller implements the idea of the ESUP Portail's 
  29.  * Logout patch to allow for redirecting to a url on logout. It also exposes a 
  30.  * log out link to the view via the WebConstants.LOGOUT constant. 
  31.  *  
  32.  * @author Scott Battaglia 
  33.  * @version $Revision$ $Date$ 
  34.  * @since 3.0 
  35.  */  
  36. public final class LogoutController extends AbstractController {  
  37.   
  38.     /** The CORE to which we delegate for all CAS functionality. */  
  39.     @NotNull  
  40.     private CentralAuthenticationService centralAuthenticationService;  
  41.   
  42.     /** CookieGenerator for TGT Cookie */  
  43.     @NotNull  
  44.     private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;  
  45.   
  46.     /** CookieGenerator for Warn Cookie */  
  47.     @NotNull  
  48.     private CookieRetrievingCookieGenerator warnCookieGenerator;  
  49.   
  50.     /** Logout view name. */  
  51.     @NotNull  
  52.     private String logoutView;  
  53.   
  54.     <span style="color:#ff0000;">@NotNull  
  55.     private ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO;  
  56.   
  57. </span> /** 
  58.      * Boolean to determine if we will redirect to any url provided in the 
  59.      * service request parameter. 
  60.      */  
  61.     private boolean followServiceRedirects;  
  62.   
  63.     public LogoutController() {  
  64.         setCacheSeconds(0);  
  65.     }  
  66.   
  67.     protected ModelAndView handleRequestInternal(  
  68.             final HttpServletRequest request, final HttpServletResponse response)  
  69.             throws Exception {  
  70.         final String ticketGrantingTicketId = this.ticketGrantingTicketCookieGenerator  
  71.                 .retrieveCookieValue(request);  
  72.         final String service = request.getParameter("service");  
  73.         // change token status  
  74.         try {  
  75.             <span style="color:#ff0000;">UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials) this.centralAuthenticationService.getCredentials();  
  76.             Assert.notNull(userinfo,"userinfo is null");  
  77.             this.modifyLoginedStatusAttributeDAO.updateToken(userinfo.getUsername(), "0");  
  78. </span>     } catch (Exception e) {  
  79.             e.printStackTrace();  
  80.         }  
  81.         if (ticketGrantingTicketId != null) {  
  82.             this.centralAuthenticationService  
  83.                     .destroyTicketGrantingTicket(ticketGrantingTicketId);  
  84.   
  85.             this.ticketGrantingTicketCookieGenerator.removeCookie(response);  
  86.             this.warnCookieGenerator.removeCookie(response);  
  87.         }  
  88.   
  89.         if (this.followServiceRedirects && service != null) {  
  90.             return new ModelAndView(new RedirectView(service));  
  91.         }  
  92.   
  93.         return new ModelAndView(this.logoutView);  
  94.     }  
  95.   
  96.     public void setTicketGrantingTicketCookieGenerator(  
  97.             final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) {  
  98.         this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator;  
  99.     }  
  100.   
  101.     public void setWarnCookieGenerator(  
  102.             final CookieRetrievingCookieGenerator warnCookieGenerator) {  
  103.         this.warnCookieGenerator = warnCookieGenerator;  
  104.     }  
  105.   
  106.     /** 
  107.      * @param centralAuthenticationService 
  108.      *            The centralAuthenticationService to set. 
  109.      */  
  110.     public void setCentralAuthenticationService(  
  111.             final CentralAuthenticationService centralAuthenticationService) {  
  112.         this.centralAuthenticationService = centralAuthenticationService;  
  113.     }  
  114.   
  115.     public void setFollowServiceRedirects(final boolean followServiceRedirects) {  
  116.         this.followServiceRedirects = followServiceRedirects;  
  117.     }  
  118.   
  119.     public void setLogoutView(final String logoutView) {  
  120.         this.logoutView = logoutView;  
  121.     }  
  122.   
  123.     public void setModifyLoginedStatusAttributeDAO(  
  124.             ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO) {  
  125.         this.modifyLoginedStatusAttributeDAO = modifyLoginedStatusAttributeDAO;  
  126.     }  
  127.   
  128.     public ModifyLoginedStatusAttributeDAO getModifyLoginedStatusAttributeDAO() {  
  129.         return modifyLoginedStatusAttributeDAO;  
  130.     }  
  131. }  
/*
 * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
 * distributed with this file and available online at
 * http://www.ja-sig.org/products/cas/overview/license/
 */
package org.jasig.cas.web;

import java.util.Map;

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

import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.jasig.services.persondir.support.jdbc.ModifyLoginedStatusAttributeDAO;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 * Controller to delete ticket granting ticket cookie in order to log out of
 * single sign on. This controller implements the idea of the ESUP Portail's
 * Logout patch to allow for redirecting to a url on logout. It also exposes a
 * log out link to the view via the WebConstants.LOGOUT constant.
 * 
 * @author Scott Battaglia
 * @version $Revision$ $Date$
 * @since 3.0
 */
public final class LogoutController extends AbstractController {

	/** The CORE to which we delegate for all CAS functionality. */
	@NotNull
	private CentralAuthenticationService centralAuthenticationService;

	/** CookieGenerator for TGT Cookie */
	@NotNull
	private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;

	/** CookieGenerator for Warn Cookie */
	@NotNull
	private CookieRetrievingCookieGenerator warnCookieGenerator;

	/** Logout view name. */
	@NotNull
	private String logoutView;

	@NotNull
	private ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO;

	/**
	 * Boolean to determine if we will redirect to any url provided in the
	 * service request parameter.
	 */
	private boolean followServiceRedirects;

	public LogoutController() {
		setCacheSeconds(0);
	}

	protected ModelAndView handleRequestInternal(
			final HttpServletRequest request, final HttpServletResponse response)
			throws Exception {
		final String ticketGrantingTicketId = this.ticketGrantingTicketCookieGenerator
				.retrieveCookieValue(request);
		final String service = request.getParameter("service");
		// change token status
		try {
			UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials) this.centralAuthenticationService.getCredentials();
			Assert.notNull(userinfo,"userinfo is null");
			this.modifyLoginedStatusAttributeDAO.updateToken(userinfo.getUsername(), "0");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (ticketGrantingTicketId != null) {
			this.centralAuthenticationService
					.destroyTicketGrantingTicket(ticketGrantingTicketId);

			this.ticketGrantingTicketCookieGenerator.removeCookie(response);
			this.warnCookieGenerator.removeCookie(response);
		}

		if (this.followServiceRedirects && service != null) {
			return new ModelAndView(new RedirectView(service));
		}

		return new ModelAndView(this.logoutView);
	}

	public void setTicketGrantingTicketCookieGenerator(
			final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) {
		this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator;
	}

	public void setWarnCookieGenerator(
			final CookieRetrievingCookieGenerator warnCookieGenerator) {
		this.warnCookieGenerator = warnCookieGenerator;
	}

	/**
	 * @param centralAuthenticationService
	 *            The centralAuthenticationService to set.
	 */
	public void setCentralAuthenticationService(
			final CentralAuthenticationService centralAuthenticationService) {
		this.centralAuthenticationService = centralAuthenticationService;
	}

	public void setFollowServiceRedirects(final boolean followServiceRedirects) {
		this.followServiceRedirects = followServiceRedirects;
	}

	public void setLogoutView(final String logoutView) {
		this.logoutView = logoutView;
	}

	public void setModifyLoginedStatusAttributeDAO(
			ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO) {
		this.modifyLoginedStatusAttributeDAO = modifyLoginedStatusAttributeDAO;
	}

	public ModifyLoginedStatusAttributeDAO getModifyLoginedStatusAttributeDAO() {
		return modifyLoginedStatusAttributeDAO;
	}
}

cas-servlet.xml的改动部分主要是将datasource和对应的数据库注入相关的bean里面。


 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:webflow="http://www.springframework.org/schema/webflow-config"  
  5.        xmlns:p="http://www.springframework.org/schema/p"         
  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.        http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">  
  8.   
  9.     <import resource="spring-configuration/propertyFileConfigurer.xml" />  
  10.   
  11.     <!-- Theme Resolver -->  
  12.     <bean id="themeResolver" class="org.jasig.cas.services.web.ServiceThemeResolver"  
  13.         p:defaultThemeName="${cas.themeResolver.defaultThemeName}"  
  14.         p:argumentExtractors-ref="argumentExtractors"  
  15.         p:servicesManager-ref="servicesManager">  
  16.         <property name="mobileBrowsers">  
  17.             <map>  
  18.                 <entry key=".*iPhone.*" value="iphone" />  
  19.                 <entry key=".*Android.*" value="iphone" />  
  20.                 <entry key=".*Safari.*Pre.*" value="iphone" />  
  21.                 <entry key=".*Nokia.*AppleWebKit.*" value="iphone" />  
  22.             </map>  
  23.         </property>  
  24.     </bean>  
  25.   
  26.     <!-- View Resolver -->  
  27.     <bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"  
  28.         p:order="0">  
  29.         <property name="basenames">  
  30.             <list>  
  31.                 <value>${cas.viewResolver.basename}</value>  
  32.                 <value>protocol_views</value>  
  33.             </list>  
  34.         </property>  
  35.     </bean>  
  36.       
  37.     <!-- Locale Resolver -->  
  38.     <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />  
  39.           
  40.     <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />  
  41.       
  42.     <bean id="urlBasedViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"  
  43.         p:viewClass="org.springframework.web.servlet.view.InternalResourceView"  
  44.         p:prefix="/WEB-INF/view/jsp/"  
  45.         p:suffix=".jsp"  
  46.         p:order="1"/>  
  47.       
  48.     <bean id="errorHandlerResolver" class="org.jasig.cas.web.NoSuchFlowExecutionExceptionResolver" />  
  49.   
  50.     <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />  
  51.       
  52.     <bean  
  53.         id="handlerMappingC"  
  54.         class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">  
  55.         <property  
  56.             name="mappings">  
  57.             <props>  
  58.                 <prop  
  59.                     key="/logout">  
  60.                     logoutController  
  61.                 </prop>  
  62.                 <prop  
  63.                     key="/serviceValidate">  
  64.                     serviceValidateController  
  65.                 </prop>  
  66.                 <prop  
  67.                     key="/validate">  
  68.                     legacyValidateController  
  69.                 </prop>  
  70.                 <prop  
  71.                     key="/proxy">  
  72.                     proxyController  
  73.                 </prop>  
  74.                 <prop  
  75.                     key="/proxyValidate">  
  76.                     proxyValidateController  
  77.                 </prop>  
  78.                 <prop  
  79.                     key="/samlValidate">  
  80.                     samlValidateController  
  81.                 </prop>  
  82.                   
  83.                 <prop  
  84.                     key="/services/add.html">  
  85.                     addRegisteredServiceSimpleFormController  
  86.                 </prop>  
  87.                   
  88.                 <prop  
  89.                     key="/services/edit.html">  
  90.                     editRegisteredServiceSimpleFormController  
  91.                 </prop>  
  92.                   
  93.                 <prop  
  94.                     key="/services/loggedOut.html">  
  95.                     serviceLogoutViewController  
  96.                 </prop>  
  97.   
  98.                 <prop key="/services/viewStatistics.html">  
  99.                     viewStatisticsController  
  100.                 </prop>  
  101.               
  102.                 <prop key="/services/*">manageRegisteredServicesMultiActionController</prop>  
  103.                 <prop key="/openid/*">openIdProviderController</prop>  
  104.                 <prop key="/authorizationFailure.html">passThroughController</prop>  
  105.                 <prop key="/403.html">passThroughController</prop>  
  106.             </props>  
  107.         </property>  
  108.         <property  
  109.             name="alwaysUseFullPath" value="true" />  
  110.         <!--  
  111.         uncomment this to enable sending PageRequest events.   
  112.         <property  
  113.             name="interceptors">  
  114.             <list>  
  115.                 <ref bean="pageRequestHandlerInterceptorAdapter" />  
  116.             </list>  
  117.         </property>  
  118.          -->  
  119.     </bean>  
  120.   
  121.     <bean id="passThroughController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />   
  122.       
  123.     <bean  
  124.         id="openIdProviderController"  
  125.         class="org.jasig.cas.web.OpenIdProviderController"  
  126.         p:loginUrl="${cas.securityContext.casProcessingFilterEntryPoint.loginUrl}" />  
  127.       
  128.     <bean  
  129.         id="serviceLogoutViewController"  
  130.         class="org.springframework.web.servlet.mvc.ParameterizableViewController"  
  131.         p:viewName="serviceLogoutView" />  
  132.   
  133.     <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping" p:flowRegistry-ref="flowRegistry" p:order="2">  
  134.         <property name="interceptors">  
  135.             <ref local="localeChangeInterceptor" />  
  136.         </property>  
  137.     </bean>  
  138.   
  139.   
  140.      <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter"  
  141.         p:flowExecutor-ref="flowExecutor"  
  142.         p:flowUrlHandler-ref="flowUrlHandler" />  
  143.    
  144.     <bean id="flowUrlHandler" class="org.jasig.cas.web.flow.CasDefaultFlowUrlHandler" />  
  145.   
  146.     <webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">  
  147.         <webflow:flow-execution-attributes>  
  148.             <webflow:always-redirect-on-pause value="false" />  
  149.         </webflow:flow-execution-attributes>  
  150.     </webflow:flow-executor>  
  151.   
  152.     <webflow:flow-registry id="flowRegistry" flow-builder-services="builder">  
  153.         <webflow:flow-location path="/WEB-INF/login-webflow.xml" id="login" />  
  154.     </webflow:flow-registry>  
  155.   
  156.     <webflow:flow-builder-services id="builder" view-factory-creator="viewFactoryCreator" expression-parser="expressionParser" />  
  157.   
  158.     <bean id="expressionParser" class="org.springframework.webflow.expression.WebFlowOgnlExpressionParser" />  
  159.   
  160.     <bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">  
  161.         <property name="viewResolvers">  
  162.             <list>  
  163.                 <ref local="viewResolver" />  
  164.             </list>  
  165.         </property>  
  166.     </bean>  
  167.     <bean id="proxyValidateController" class="org.jasig.cas.web.ServiceValidateController"  
  168.         p:centralAuthenticationService-ref="centralAuthenticationService"  
  169.         p:proxyHandler-ref="proxy20Handler"  
  170.         p:argumentExtractor-ref="casArgumentExtractor" />  
  171.   
  172.     <bean id="serviceValidateController" class="org.jasig.cas.web.ServiceValidateController"  
  173.         p:validationSpecificationClass="org.jasig.cas.validation.Cas20WithoutProxyingValidationSpecification"  
  174.         p:centralAuthenticationService-ref="centralAuthenticationService"  
  175.         p:proxyHandler-ref="proxy20Handler"  
  176.         p:argumentExtractor-ref="casArgumentExtractor" />  
  177.       
  178.     <bean id="samlValidateController" class="org.jasig.cas.web.ServiceValidateController"  
  179.         p:validationSpecificationClass="org.jasig.cas.validation.Cas20WithoutProxyingValidationSpecification"  
  180.         p:centralAuthenticationService-ref="centralAuthenticationService"  
  181.         p:proxyHandler-ref="proxy20Handler"  
  182.         p:argumentExtractor-ref="samlArgumentExtractor"  
  183.         p:successView="casSamlServiceSuccessView"  
  184.         p:failureView="casSamlServiceFailureView" />  
  185.   
  186.     <bean id="legacyValidateController" class="org.jasig.cas.web.ServiceValidateController"  
  187.         p:proxyHandler-ref="proxy10Handler"  
  188.         p:successView="cas1ServiceSuccessView"  
  189.         p:failureView="cas1ServiceFailureView"  
  190.         p:validationSpecificationClass="org.jasig.cas.validation.Cas10ProtocolValidationSpecification"  
  191.         p:centralAuthenticationService-ref="centralAuthenticationService"  
  192.         p:argumentExtractor-ref="casArgumentExtractor" />  
  193.   
  194.     <bean id="proxyController" class="org.jasig.cas.web.ProxyController"  
  195.         p:centralAuthenticationService-ref="centralAuthenticationService" />  
  196.   
  197.     <bean id="viewStatisticsController" class="org.jasig.cas.web.StatisticsController"  
  198.         p:casTicketSuffix="${host.name}">  
  199.         <constructor-arg index="0" ref="ticketRegistry" />  
  200.     </bean>  
  201.   
  202.     <bean id="logoutController" class="org.jasig.cas.web.LogoutController"  
  203.         p:centralAuthenticationService-ref="centralAuthenticationService"  
  204.         p:logoutView="casLogoutView"  
  205.         p:followServiceRedirects="true"    
  206.         p:warnCookieGenerator-ref="warnCookieGenerator"  
  207.         p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator"  
  208.         <span style="color:#ff6600;">p:modifyLoginedStatusAttributeDAO-ref="modifyLoginedStatusAttributeDAO"  
  209. </span>     />  
  210.       
  211.     <bean id="initialFlowSetupAction" class="org.jasig.cas.web.flow.InitialFlowSetupAction"  
  212.         p:argumentExtractors-ref="argumentExtractors"  
  213.         p:warnCookieGenerator-ref="warnCookieGenerator"  
  214.         p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator" />  
  215.       
  216.     <bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"  
  217.         p:centralAuthenticationService-ref="centralAuthenticationService"  
  218.         p:warnCookieGenerator-ref="warnCookieGenerator" />  
  219.       
  220.     <bean id="generateServiceTicketAction" class="org.jasig.cas.web.flow.GenerateServiceTicketAction"  
  221.         p:centralAuthenticationService-ref="centralAuthenticationService"  
  222.         <span style="color:#ff0000;">p:applicationAuthoritiedAuthenticationDAO-ref="applicationAuthoritiedAuthenticationDAO"  
  223. </span>      />  
  224.           
  225.     <bean id="sendTicketGrantingTicketAction" class="org.jasig.cas.web.flow.SendTicketGrantingTicketAction"  
  226.         p:centralAuthenticationService-ref="centralAuthenticationService"  
  227.         p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator" />  
  228.   
  229.     <bean id="gatewayServicesManagementCheck" class="org.jasig.cas.web.flow.GatewayServicesManagementCheck">  
  230.         <constructor-arg index="0" ref="servicesManager" />  
  231.     </bean>  
  232.           
  233.     <bean id="generateLoginTicketAction" class="org.jasig.cas.web.flow.GenerateLoginTicketAction"  
  234.         p:ticketIdGenerator-ref="loginTicketUniqueIdGenerator" />  
  235.       
  236.     <bean id="addRegisteredServiceSimpleFormController" class="org.jasig.cas.services.web.RegisteredServiceSimpleFormController"  
  237.         p:formView="addServiceView"  
  238.         p:successView="addServiceView"  
  239.         p:commandName="registeredService"  
  240.         p:validator-ref="registeredServiceValidator"  
  241.         p:sessionForm="true">  
  242.         <constructor-arg index="0" ref="servicesManager" />  
  243.         <constructor-arg index="1" ref="attributeRepository" />  
  244.     </bean>  
  245.       
  246.     <bean id="editRegisteredServiceSimpleFormController" class="org.jasig.cas.services.web.RegisteredServiceSimpleFormController"  
  247.         p:formView="editServiceView"  
  248.         p:successView="editServiceView"  
  249.         p:commandName="registeredService"  
  250.         p:validator-ref="registeredServiceValidator"  
  251.         p:sessionForm="false">  
  252.         <constructor-arg index="0" ref="servicesManager" />  
  253.         <constructor-arg index="1" ref="attributeRepository" />  
  254.     </bean>  
  255.       
  256.     <bean id="registeredServiceValidator" class="org.jasig.cas.services.web.support.RegisteredServiceValidator"  
  257.         p:servicesManager-ref="servicesManager" />  
  258.       
  259.     <bean id="manageRegisteredServicesMultiActionController" class="org.jasig.cas.services.web.ManageRegisteredServicesMultiActionController">  
  260.         <constructor-arg index="0" ref="servicesManager" />  
  261.         <constructor-arg index="1" value="${cas.securityContext.serviceProperties.service}" />  
  262.     </bean>  
  263.   
  264.     <bean id="messageInterpolator" class="org.jasig.cas.util.SpringAwareMessageMessageInterpolator" />  
  265.   
  266.     <bean id="credentialsValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"  
  267.             p:messageInterpolator-ref="messageInterpolator" />  
  268. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:webflow="http://www.springframework.org/schema/webflow-config"
       xmlns:p="http://www.springframework.org/schema/p"       
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">

    <import resource="spring-configuration/propertyFileConfigurer.xml" />

	<!-- Theme Resolver -->
	<bean id="themeResolver" class="org.jasig.cas.services.web.ServiceThemeResolver"
		p:defaultThemeName="${cas.themeResolver.defaultThemeName}"
        p:argumentExtractors-ref="argumentExtractors"
        p:servicesManager-ref="servicesManager">
        <property name="mobileBrowsers">
            <map>
                <entry key=".*iPhone.*" value="iphone" />
                <entry key=".*Android.*" value="iphone" />
                <entry key=".*Safari.*Pre.*" value="iphone" />
                <entry key=".*Nokia.*AppleWebKit.*" value="iphone" />
            </map>
        </property>
    </bean>

	<!-- View Resolver -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"
		p:order="0">
		<property name="basenames">
			<list>
				<value>${cas.viewResolver.basename}</value>
				<value>protocol_views</value>
			</list>
		</property>
	</bean>
	
	<!-- Locale Resolver -->
	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
		
	<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
	
	<bean id="urlBasedViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"
		p:viewClass="org.springframework.web.servlet.view.InternalResourceView"
        p:prefix="/WEB-INF/view/jsp/"
        p:suffix=".jsp"
        p:order="1"/>
	
	<bean id="errorHandlerResolver" class="org.jasig.cas.web.NoSuchFlowExecutionExceptionResolver" />

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
	
	<bean
		id="handlerMappingC"
		class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property
			name="mappings">
			<props>
				<prop
					key="/logout">
					logoutController
				</prop>
				<prop
					key="/serviceValidate">
					serviceValidateController
				</prop>
				<prop
					key="/validate">
					legacyValidateController
				</prop>
				<prop
					key="/proxy">
					proxyController
				</prop>
				<prop
					key="/proxyValidate">
					proxyValidateController
				</prop>
				<prop
					key="/samlValidate">
					samlValidateController
				</prop>
				
				<prop
					key="/services/add.html">
					addRegisteredServiceSimpleFormController
				</prop>
				
				<prop
					key="/services/edit.html">
					editRegisteredServiceSimpleFormController
				</prop>
				
				<prop
					key="/services/loggedOut.html">
					serviceLogoutViewController
				</prop>

                <prop key="/services/viewStatistics.html">
                    viewStatisticsController
                </prop>
			
				<prop key="/services/*">manageRegisteredServicesMultiActionController</prop>
				<prop key="/openid/*">openIdProviderController</prop>
                <prop key="/authorizationFailure.html">passThroughController</prop>
                <prop key="/403.html">passThroughController</prop>
			</props>
		</property>
		<property
			name="alwaysUseFullPath" value="true" />
		<!--
		uncomment this to enable sending PageRequest events. 
		<property
			name="interceptors">
			<list>
				<ref bean="pageRequestHandlerInterceptorAdapter" />
			</list>
		</property>
		 -->
	</bean>

    <bean id="passThroughController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" /> 
	
	<bean
		id="openIdProviderController"
		class="org.jasig.cas.web.OpenIdProviderController"
		p:loginUrl="${cas.securityContext.casProcessingFilterEntryPoint.loginUrl}" />
	
	<bean
		id="serviceLogoutViewController"
		class="org.springframework.web.servlet.mvc.ParameterizableViewController"
		p:viewName="serviceLogoutView" />

    <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping" p:flowRegistry-ref="flowRegistry" p:order="2">
        <property name="interceptors">
            <ref local="localeChangeInterceptor" />
        </property>
    </bean>


     <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter"
        p:flowExecutor-ref="flowExecutor"
        p:flowUrlHandler-ref="flowUrlHandler" />
 
    <bean id="flowUrlHandler" class="org.jasig.cas.web.flow.CasDefaultFlowUrlHandler" />

    <webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">
        <webflow:flow-execution-attributes>
            <webflow:always-redirect-on-pause value="false" />
        </webflow:flow-execution-attributes>
    </webflow:flow-executor>

    <webflow:flow-registry id="flowRegistry" flow-builder-services="builder">
        <webflow:flow-location path="/WEB-INF/login-webflow.xml" id="login" />
    </webflow:flow-registry>

    <webflow:flow-builder-services id="builder" view-factory-creator="viewFactoryCreator" expression-parser="expressionParser" />

    <bean id="expressionParser" class="org.springframework.webflow.expression.WebFlowOgnlExpressionParser" />

    <bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
        <property name="viewResolvers">
            <list>
                <ref local="viewResolver" />
            </list>
        </property>
    </bean>
	<bean id="proxyValidateController" class="org.jasig.cas.web.ServiceValidateController"
		p:centralAuthenticationService-ref="centralAuthenticationService"
		p:proxyHandler-ref="proxy20Handler"
		p:argumentExtractor-ref="casArgumentExtractor" />

	<bean id="serviceValidateController" class="org.jasig.cas.web.ServiceValidateController"
		p:validationSpecificationClass="org.jasig.cas.validation.Cas20WithoutProxyingValidationSpecification"
		p:centralAuthenticationService-ref="centralAuthenticationService"
		p:proxyHandler-ref="proxy20Handler"
		p:argumentExtractor-ref="casArgumentExtractor" />
	
	<bean id="samlValidateController" class="org.jasig.cas.web.ServiceValidateController"
		p:validationSpecificationClass="org.jasig.cas.validation.Cas20WithoutProxyingValidationSpecification"
		p:centralAuthenticationService-ref="centralAuthenticationService"
		p:proxyHandler-ref="proxy20Handler"
		p:argumentExtractor-ref="samlArgumentExtractor"
		p:successView="casSamlServiceSuccessView"
		p:failureView="casSamlServiceFailureView" />

	<bean id="legacyValidateController" class="org.jasig.cas.web.ServiceValidateController"
		p:proxyHandler-ref="proxy10Handler"
		p:successView="cas1ServiceSuccessView"
		p:failureView="cas1ServiceFailureView"
		p:validationSpecificationClass="org.jasig.cas.validation.Cas10ProtocolValidationSpecification"
		p:centralAuthenticationService-ref="centralAuthenticationService"
		p:argumentExtractor-ref="casArgumentExtractor" />

	<bean id="proxyController" class="org.jasig.cas.web.ProxyController"
		p:centralAuthenticationService-ref="centralAuthenticationService" />

    <bean id="viewStatisticsController" class="org.jasig.cas.web.StatisticsController"
        p:casTicketSuffix="${host.name}">
        <constructor-arg index="0" ref="ticketRegistry" />
    </bean>

	<bean id="logoutController" class="org.jasig.cas.web.LogoutController"
		p:centralAuthenticationService-ref="centralAuthenticationService"
		p:logoutView="casLogoutView"
		p:followServiceRedirects="true"  
		p:warnCookieGenerator-ref="warnCookieGenerator"
		p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator"
		p:modifyLoginedStatusAttributeDAO-ref="modifyLoginedStatusAttributeDAO"
		/>
	
	<bean id="initialFlowSetupAction" class="org.jasig.cas.web.flow.InitialFlowSetupAction"
		p:argumentExtractors-ref="argumentExtractors"
		p:warnCookieGenerator-ref="warnCookieGenerator"
		p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator" />
	
	<bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"
		p:centralAuthenticationService-ref="centralAuthenticationService"
		p:warnCookieGenerator-ref="warnCookieGenerator" />
	
	<bean id="generateServiceTicketAction" class="org.jasig.cas.web.flow.GenerateServiceTicketAction"
		p:centralAuthenticationService-ref="centralAuthenticationService"
		p:applicationAuthoritiedAuthenticationDAO-ref="applicationAuthoritiedAuthenticationDAO"
		 />
		
	<bean id="sendTicketGrantingTicketAction" class="org.jasig.cas.web.flow.SendTicketGrantingTicketAction"
		p:centralAuthenticationService-ref="centralAuthenticationService"
		p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator" />

    <bean id="gatewayServicesManagementCheck" class="org.jasig.cas.web.flow.GatewayServicesManagementCheck">
        <constructor-arg index="0" ref="servicesManager" />
    </bean>
		
	<bean id="generateLoginTicketAction" class="org.jasig.cas.web.flow.GenerateLoginTicketAction"
		p:ticketIdGenerator-ref="loginTicketUniqueIdGenerator" />
	
	<bean id="addRegisteredServiceSimpleFormController" class="org.jasig.cas.services.web.RegisteredServiceSimpleFormController"
		p:formView="addServiceView"
		p:successView="addServiceView"
		p:commandName="registeredService"
		p:validator-ref="registeredServiceValidator"
		p:sessionForm="true">
		<constructor-arg index="0" ref="servicesManager" />
		<constructor-arg index="1" ref="attributeRepository" />
	</bean>
	
	<bean id="editRegisteredServiceSimpleFormController" class="org.jasig.cas.services.web.RegisteredServiceSimpleFormController"
		p:formView="editServiceView"
		p:successView="editServiceView"
		p:commandName="registeredService"
		p:validator-ref="registeredServiceValidator"
		p:sessionForm="false">
		<constructor-arg index="0" ref="servicesManager" />
		<constructor-arg index="1" ref="attributeRepository" />
	</bean>
	
	<bean id="registeredServiceValidator" class="org.jasig.cas.services.web.support.RegisteredServiceValidator"
		p:servicesManager-ref="servicesManager" />
	
	<bean id="manageRegisteredServicesMultiActionController" class="org.jasig.cas.services.web.ManageRegisteredServicesMultiActionController">
		<constructor-arg index="0" ref="servicesManager" />
        <constructor-arg index="1" value="${cas.securityContext.serviceProperties.service}" />
	</bean>

    <bean id="messageInterpolator" class="org.jasig.cas.util.SpringAwareMessageMessageInterpolator" />

    <bean id="credentialsValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
            p:messageInterpolator-ref="messageInterpolator" />
</beans>

总结,只要明白了整个CAS的工作原理,就可以相应的改造部分内容来为我所用,CAS操作数据库部分本身提供的模板已经相当强大,但是为了方便自己用,在这里写了两个类来封装操作数据库的操作。

上面写完了登录验证。那么接下来还有几个部分需要修改。  
当用户登录成功之后从应用1跳转到应用2的时候也需要增加一个判断应用2是否授权的操作。具体是在GenerateServiceTicketAction.java类中。
当用户退出的时候(包括浏览器退出都要触发LogoutController.java类中的操作)因此退出的时候一定要更改用户的登录状态,负责下一次用户将无法登录。
其他的如果你有其他的地方需要改造,那么不管是login-webflow.xml,还是cas-servlet.xml.都可以相应的更改。
将核心代码展示如下:
GenerateServiceTicketAction.Java
[java] view plain copy
 
/* 
 * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license 
 * distributed with this file and available online at 
 * http://www.ja-sig.org/products/cas/overview/license/ 
 */  
package org.jasig.cas.web.flow;  
  
import java.net.MalformedURLException;  
import java.net.URL;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  
import org.apache.commons.logging.LogFactory;  
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.support.WebUtils;  
import org.jasig.services.persondir.support.jdbc.ApplicationAuthoritiedAuthenticationDAO;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;  
import org.springframework.util.Assert;  
import org.springframework.util.StringUtils;  
import org.springframework.webflow.action.AbstractAction;  
import org.springframework.webflow.execution.Event;  
import org.springframework.webflow.execution.RequestContext;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.sql.DataSource;  
import javax.validation.constraints.NotNull;  
  
/** 
 * Action to generate a service ticket for a given Ticket Granting Ticket and 
 * Service. 
 *  
 * @author Scott Battaglia 
 * @version $Revision$ $Date$ 
 * @since 3.0.4 
 */  
public final class GenerateServiceTicketAction extends AbstractAction {  
     
    private final Logger log = LoggerFactory.getLogger(this.getClass());  
    /** Instance of CentralAuthenticationService. */  
    @NotNull  
    private CentralAuthenticationService centralAuthenticationService;  
  
    /** Instance of ApplicationAuthoritiedAuthenticationDAO. */  
    @NotNull  
    <span style="color:#000099;">private ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO;  
      
</span>    /** check the url your are request is valid or not*/  
   <span style="color:#ff0000;"> protected boolean checkUrl(final RequestContext context){  
        UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials)this.centralAuthenticationService.getCredentials();  
        HttpServletRequest request = WebUtils.getHttpServletRequest(context);  
        String url = request.getParameter("service").toString();  
        Assert.notNull(userinfo,"userinfo is null");  
        Assert.notNull(url,"url is null");  
          
        boolean result = this.applicationAuthoritiedAuthenticationDAO.CheckApplicationURLIsAuthority(url, userinfo.getUsername());  
        if(result){  
            log.error("Your have no authoriation to log this application");  
            return false;  
        }  
        log.info("the Url is valid\n");  
        return true;  
    }  
</span>    protected Event doExecute(final RequestContext context) {  
          
        <span style="color:#ff0000;">boolean result = checkUrl(context);  
        if(!result){  
            return error();  
        }  
</span>        final Service service = WebUtils.getService(context);  
        final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);  
  
        try {  
            final String serviceTicketId = this.centralAuthenticationService  
                .grantServiceTicket(ticketGrantingTicket,  
                    service);  
            WebUtils.putServiceTicketInRequestScope(context,  
                serviceTicketId);  
            return success();  
        } catch (final TicketException e) {  
            if (isGatewayPresent(context)) {  
                return result("gateway");  
            }  
        }  
  
        return error();  
    }  
  
    public void setCentralAuthenticationService(  
        final CentralAuthenticationService centralAuthenticationService) {  
        this.centralAuthenticationService = centralAuthenticationService;  
    }  
  
    protected boolean isGatewayPresent(final RequestContext context) {  
        return StringUtils.hasText(context.getExternalContext()  
            .getRequestParameterMap().get("gateway"));  
    }  
      
    public void setApplicationAuthoritiedAuthenticationDAO(  
            ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO) {  
        this.applicationAuthoritiedAuthenticationDAO = applicationAuthoritiedAuthenticationDAO;  
    }  
    public ApplicationAuthoritiedAuthenticationDAO getApplicationAuthoritiedAuthenticationDAO() {  
        return applicationAuthoritiedAuthenticationDAO;  
    }  
}  
LogoutController.java
[java] view plain copy
 
/* 
 * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license 
 * distributed with this file and available online at 
 * http://www.ja-sig.org/products/cas/overview/license/ 
 */  
package org.jasig.cas.web;  
  
import java.util.Map;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.sql.DataSource;  
import javax.validation.constraints.NotNull;  
  
import org.jasig.cas.CentralAuthenticationService;  
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;  
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;  
import org.jasig.services.persondir.support.jdbc.ModifyLoginedStatusAttributeDAO;  
import org.springframework.jdbc.core.JdbcTemplate;  
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;  
import org.springframework.util.Assert;  
import org.springframework.web.servlet.ModelAndView;  
import org.springframework.web.servlet.mvc.AbstractController;  
import org.springframework.web.servlet.view.RedirectView;  
  
/** 
 * Controller to delete ticket granting ticket cookie in order to log out of 
 * single sign on. This controller implements the idea of the ESUP Portail's 
 * Logout patch to allow for redirecting to a url on logout. It also exposes a 
 * log out link to the view via the WebConstants.LOGOUT constant. 
 *  
 * @author Scott Battaglia 
 * @version $Revision$ $Date$ 
 * @since 3.0 
 */  
public final class LogoutController extends AbstractController {  
  
    /** The CORE to which we delegate for all CAS functionality. */  
    @NotNull  
    private CentralAuthenticationService centralAuthenticationService;  
  
    /** CookieGenerator for TGT Cookie */  
    @NotNull  
    private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;  
  
    /** CookieGenerator for Warn Cookie */  
    @NotNull  
    private CookieRetrievingCookieGenerator warnCookieGenerator;  
  
    /** Logout view name. */  
    @NotNull  
    private String logoutView;  
  
    <span style="color:#ff0000;">@NotNull  
    private ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO;  
  
</span> /** 
     * Boolean to determine if we will redirect to any url provided in the 
     * service request parameter. 
     */  
    private boolean followServiceRedirects;  
  
    public LogoutController() {  
        setCacheSeconds(0);  
    }  
  
    protected ModelAndView handleRequestInternal(  
            final HttpServletRequest request, final HttpServletResponse response)  
            throws Exception {  
        final String ticketGrantingTicketId = this.ticketGrantingTicketCookieGenerator  
                .retrieveCookieValue(request);  
        final String service = request.getParameter("service");  
        // change token status  
        try {  
            <span style="color:#ff0000;">UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials) this.centralAuthenticationService.getCredentials();  
            Assert.notNull(userinfo,"userinfo is null");  
            this.modifyLoginedStatusAttributeDAO.updateToken(userinfo.getUsername(), "0");  
</span>     } catch (Exception e) {  
            e.printStackTrace();  
        }  
        if (ticketGrantingTicketId != null) {  
            this.centralAuthenticationService  
                    .destroyTicketGrantingTicket(ticketGrantingTicketId);  
  
            this.ticketGrantingTicketCookieGenerator.removeCookie(response);  
            this.warnCookieGenerator.removeCookie(response);  
        }  
  
        if (this.followServiceRedirects && service != null) {  
            return new ModelAndView(new RedirectView(service));  
        }  
  
        return new ModelAndView(this.logoutView);  
    }  
  
    public void setTicketGrantingTicketCookieGenerator(  
            final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) {  
        this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator;  
    }  
  
    public void setWarnCookieGenerator(  
            final CookieRetrievingCookieGenerator warnCookieGenerator) {  
        this.warnCookieGenerator = warnCookieGenerator;  
    }  
  
    /** 
     * @param centralAuthenticationService 
     *            The centralAuthenticationService to set. 
     */  
    public void setCentralAuthenticationService(  
            final CentralAuthenticationService centralAuthenticationService) {  
        this.centralAuthenticationService = centralAuthenticationService;  
    }  
  
    public void setFollowServiceRedirects(final boolean followServiceRedirects) {  
        this.followServiceRedirects = followServiceRedirects;  
    }  
  
    public void setLogoutView(final String logoutView) {  
        this.logoutView = logoutView;  
    }  
  
    public void setModifyLoginedStatusAttributeDAO(  
            ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO) {  
        this.modifyLoginedStatusAttributeDAO = modifyLoginedStatusAttributeDAO;  
    }  
  
    public ModifyLoginedStatusAttributeDAO getModifyLoginedStatusAttributeDAO() {  
        return modifyLoginedStatusAttributeDAO;  
    }  
}  
cas-servlet.xml的改动部分主要是将datasource和对应的数据库注入相关的bean里面。
 
[html] view plain copy
 
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:webflow="http://www.springframework.org/schema/webflow-config"  
       xmlns:p="http://www.springframework.org/schema/p"         
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
       http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">  
  
    <import resource="spring-configuration/propertyFileConfigurer.xml" />  
  
    <!-- Theme Resolver -->  
    <bean id="themeResolver" class="org.jasig.cas.services.web.ServiceThemeResolver"  
        p:defaultThemeName="${cas.themeResolver.defaultThemeName}"  
        p:argumentExtractors-ref="argumentExtractors"  
        p:servicesManager-ref="servicesManager">  
        <property name="mobileBrowsers">  
            <map>  
                <entry key=".*iPhone.*" value="iphone" />  
                <entry key=".*Android.*" value="iphone" />  
                <entry key=".*Safari.*Pre.*" value="iphone" />  
                <entry key=".*Nokia.*AppleWebKit.*" value="iphone" />  
            </map>  
        </property>  
    </bean>  
  
    <!-- View Resolver -->  
    <bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"  
        p:order="0">  
        <property name="basenames">  
            <list>  
                <value>${cas.viewResolver.basename}</value>  
                <value>protocol_views</value>  
            </list>  
        </property>  
    </bean>  
      
    <!-- Locale Resolver -->  
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />  
          
    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />  
      
    <bean id="urlBasedViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"  
        p:viewClass="org.springframework.web.servlet.view.InternalResourceView"  
        p:prefix="/WEB-INF/view/jsp/"  
        p:suffix=".jsp"  
        p:order="1"/>  
      
    <bean id="errorHandlerResolver" class="org.jasig.cas.web.NoSuchFlowExecutionExceptionResolver" />  
  
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />  
      
    <bean  
        id="handlerMappingC"  
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">  
        <property  
            name="mappings">  
            <props>  
                <prop  
                    key="/logout">  
                    logoutController  
                </prop>  
                <prop  
                    key="/serviceValidate">  
                    serviceValidateController  
                </prop>  
                <prop  
                    key="/validate">  
                    legacyValidateController  
                </prop>  
                <prop  
                    key="/proxy">  
                    proxyController  
                </prop>  
                <prop  
                    key="/proxyValidate">  
                    proxyValidateController  
                </prop>  
                <prop  
                    key="/samlValidate">  
                    samlValidateController  
                </prop>  
                  
                <prop  
                    key="/services/add.html">  
                    addRegisteredServiceSimpleFormController  
                </prop>  
                  
                <prop  
                    key="/services/edit.html">  
                    editRegisteredServiceSimpleFormController  
                </prop>  
                  
                <prop  
                    key="/services/loggedOut.html">  
                    serviceLogoutViewController  
                </prop>  
  
                <prop key="/services/viewStatistics.html">  
                    viewStatisticsController  
                </prop>  
              
                <prop key="/services/*">manageRegisteredServicesMultiActionController</prop>  
                <prop key="/openid/*">openIdProviderController</prop>  
                <prop key="/authorizationFailure.html">passThroughController</prop>  
                <prop key="/403.html">passThroughController</prop>  
            </props>  
        </property>  
        <property  
            name="alwaysUseFullPath" value="true" />  
        <!--  
        uncomment this to enable sending PageRequest events.   
        <property  
            name="interceptors">  
            <list>  
                <ref bean="pageRequestHandlerInterceptorAdapter" />  
            </list>  
        </property>  
         -->  
    </bean>  
  
    <bean id="passThroughController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />   
      
    <bean  
        id="openIdProviderController"  
        class="org.jasig.cas.web.OpenIdProviderController"  
        p:loginUrl="${cas.securityContext.casProcessingFilterEntryPoint.loginUrl}" />  
      
    <bean  
        id="serviceLogoutViewController"  
        class="org.springframework.web.servlet.mvc.ParameterizableViewController"  
        p:viewName="serviceLogoutView" />  
  
    <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping" p:flowRegistry-ref="flowRegistry" p:order="2">  
        <property name="interceptors">  
            <ref local="localeChangeInterceptor" />  
        </property>  
    </bean>  
  
  
     <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter"  
        p:flowExecutor-ref="flowExecutor"  
        p:flowUrlHandler-ref="flowUrlHandler" />  
   
    <bean id="flowUrlHandler" class="org.jasig.cas.web.flow.CasDefaultFlowUrlHandler" />  
  
    <webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">  
        <webflow:flow-execution-attributes>  
            <webflow:always-redirect-on-pause value="false" />  
        </webflow:flow-execution-attributes>  
    </webflow:flow-executor>  
  
    <webflow:flow-registry id="flowRegistry" flow-builder-services="builder">  
        <webflow:flow-location path="/WEB-INF/login-webflow.xml" id="login" />  
    </webflow:flow-registry>  
  
    <webflow:flow-builder-services id="builder" view-factory-creator="viewFactoryCreator" expression-parser="expressionParser" />  
  
    <bean id="expressionParser" class="org.springframework.webflow.expression.WebFlowOgnlExpressionParser" />  
  
    <bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">  
        <property name="viewResolvers">  
            <list>  
                <ref local="viewResolver" />  
            </list>  
        </property>  
    </bean>  
    <bean id="proxyValidateController" class="org.jasig.cas.web.ServiceValidateController"  
        p:centralAuthenticationService-ref="centralAuthenticationService"  
        p:proxyHandler-ref="proxy20Handler"  
        p:argumentExtractor-ref="casArgumentExtractor" />  
  
    <bean id="serviceValidateController" class="org.jasig.cas.web.ServiceValidateController"  
        p:validationSpecificationClass="org.jasig.cas.validation.Cas20WithoutProxyingValidationSpecification"  
        p:centralAuthenticationService-ref="centralAuthenticationService"  
        p:proxyHandler-ref="proxy20Handler"  
        p:argumentExtractor-ref="casArgumentExtractor" />  
      
    <bean id="samlValidateController" class="org.jasig.cas.web.ServiceValidateController"  
        p:validationSpecificationClass="org.jasig.cas.validation.Cas20WithoutProxyingValidationSpecification"  
        p:centralAuthenticationService-ref="centralAuthenticationService"  
        p:proxyHandler-ref="proxy20Handler"  
        p:argumentExtractor-ref="samlArgumentExtractor"  
        p:successView="casSamlServiceSuccessView"  
        p:failureView="casSamlServiceFailureView" />  
  
    <bean id="legacyValidateController" class="org.jasig.cas.web.ServiceValidateController"  
        p:proxyHandler-ref="proxy10Handler"  
        p:successView="cas1ServiceSuccessView"  
        p:failureView="cas1ServiceFailureView"  
        p:validationSpecificationClass="org.jasig.cas.validation.Cas10ProtocolValidationSpecification"  
        p:centralAuthenticationService-ref="centralAuthenticationService"  
        p:argumentExtractor-ref="casArgumentExtractor" />  
  
    <bean id="proxyController" class="org.jasig.cas.web.ProxyController"  
        p:centralAuthenticationService-ref="centralAuthenticationService" />  
  
    <bean id="viewStatisticsController" class="org.jasig.cas.web.StatisticsController"  
        p:casTicketSuffix="${host.name}">  
        <constructor-arg index="0" ref="ticketRegistry" />  
    </bean>  
  
    <bean id="logoutController" class="org.jasig.cas.web.LogoutController"  
        p:centralAuthenticationService-ref="centralAuthenticationService"  
        p:logoutView="casLogoutView"  
        p:followServiceRedirects="true"    
        p:warnCookieGenerator-ref="warnCookieGenerator"  
        p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator"  
        <span style="color:#ff6600;">p:modifyLoginedStatusAttributeDAO-ref="modifyLoginedStatusAttributeDAO"  
</span>     />  
      
    <bean id="initialFlowSetupAction" class="org.jasig.cas.web.flow.InitialFlowSetupAction"  
        p:argumentExtractors-ref="argumentExtractors"  
        p:warnCookieGenerator-ref="warnCookieGenerator"  
        p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator" />  
      
    <bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"  
        p:centralAuthenticationService-ref="centralAuthenticationService"  
        p:warnCookieGenerator-ref="warnCookieGenerator" />  
      
    <bean id="generateServiceTicketAction" class="org.jasig.cas.web.flow.GenerateServiceTicketAction"  
        p:centralAuthenticationService-ref="centralAuthenticationService"  
        <span style="color:#ff0000;">p:applicationAuthoritiedAuthenticationDAO-ref="applicationAuthoritiedAuthenticationDAO"  
</span>      />  
          
    <bean id="sendTicketGrantingTicketAction" class="org.jasig.cas.web.flow.SendTicketGrantingTicketAction"  
        p:centralAuthenticationService-ref="centralAuthenticationService"  
        p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator" />  
  
    <bean id="gatewayServicesManagementCheck" class="org.jasig.cas.web.flow.GatewayServicesManagementCheck">  
        <constructor-arg index="0" ref="servicesManager" />  
    </bean>  
          
    <bean id="generateLoginTicketAction" class="org.jasig.cas.web.flow.GenerateLoginTicketAction"  
        p:ticketIdGenerator-ref="loginTicketUniqueIdGenerator" />  
      
    <bean id="addRegisteredServiceSimpleFormController" class="org.jasig.cas.services.web.RegisteredServiceSimpleFormController"  
        p:formView="addServiceView"  
        p:successView="addServiceView"  
        p:commandName="registeredService"  
        p:validator-ref="registeredServiceValidator"  
        p:sessionForm="true">  
        <constructor-arg index="0" ref="servicesManager" />  
        <constructor-arg index="1" ref="attributeRepository" />  
    </bean>  
      
    <bean id="editRegisteredServiceSimpleFormController" class="org.jasig.cas.services.web.RegisteredServiceSimpleFormController"  
        p:formView="editServiceView"  
        p:successView="editServiceView"  
        p:commandName="registeredService"  
        p:validator-ref="registeredServiceValidator"  
        p:sessionForm="false">  
        <constructor-arg index="0" ref="servicesManager" />  
        <constructor-arg index="1" ref="attributeRepository" />  
    </bean>  
      
    <bean id="registeredServiceValidator" class="org.jasig.cas.services.web.support.RegisteredServiceValidator"  
        p:servicesManager-ref="servicesManager" />  
      
    <bean id="manageRegisteredServicesMultiActionController" class="org.jasig.cas.services.web.ManageRegisteredServicesMultiActionController">  
        <constructor-arg index="0" ref="servicesManager" />  
        <constructor-arg index="1" value="${cas.securityContext.serviceProperties.service}" />  
    </bean>  
  
    <bean id="messageInterpolator" class="org.jasig.cas.util.SpringAwareMessageMessageInterpolator" />  
  
    <bean id="credentialsValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"  
            p:messageInterpolator-ref="messageInterpolator" />  
</beans>  
总结,只要明白了整个CAS的工作原理,就可以相应的改造部分内容来为我所用,CAS操作数据库部分本身提供的模板已经相当强大,但是为了方便自己用,在这里写了两个类来封装操作数据库的操作。

猜你喜欢

转载自blog.csdn.net/superiorpengFight/article/details/53536709