CAS single sign-on source resolution "Client" __java

Source: Internet
Author: User
Tags cas getmessage ticket
Pre-Preparation:1. Cas-client-core-3.2.1.jar 2. Cas-client-3.2.1-release.zip
3. Application System WebApp (http://127.0.0.1:8090/webapp/main.do)
4.CAS single sign-on server side (http://127.0.0.1:8081/cas-server/)
This discussion includes the CAS single sign-on client part of the source code, and on this basis for two development, so need to modify some of the CAS client source code, the source code part of the changes in the following discussion. For more information on CAS server-side source analysis, please refer to another article http://blog.csdn.net/dovejing/article/details/44523545 Where Cas-client-core-3.2.1.jar is the core jar package for CAS clients, Cas-client-3.2.1-release.zip is the source code ZIP package for CAS clients. Web.xml Part of the code
	<filter> <filter-name>CASFilter</filter-name> <filter-class> Org.springframework.web.filter.delegatingfilterproxy</filter-class> </filter> <filter> < Filter-name>casvalidationfilter</filter-name> <filter-class> Org.springframework.web.filter.delegatingfilterproxy</filter-class> </filter> <filter> < Filter-name>initloginuserfilter</filter-name> <filter-class>
		Org.springframework.web.filter.delegatingfilterproxy</filter-class> </filter> <filter-mapping> <filter-name>CASFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping > <filter-mapping> <filter-name>CASValidationFilter</filter-name> <url-pattern>/*</ url-pattern> </filter-mapping> <filter-mapping> <filter-name>initloginuserfilter</ Filter-name> <url-pattern>/*</url-pattern> </fiLter-mapping>
 

Spring-context.xml Part of the code

	<bean id= "Casfilter" class= "
	com.master.client.filter.AuthenticationFilter" init-method= "Initconfig"/> <bean id= "Casvalidationfilter" class= com.master.client.filter.TicketValidationFilter "init-method=" initconfig "/>
	<bean id=" Initloginuserfilter "class=" Com.master.client.filter.InitLoginUserFilter "init-method=" Initconfig "/>

cas_config.properties Code

Service = http://127.0.0.1:8090/webapp/main.do
Casserverurlprefix = http://127.0.0.1:8081/cas-server/
Casserverloginurl = http://127.0.0.1:8081/cas-server/login
Casserverlogouturl = http://127.0.0.1:8081/ Cas-server/logout
Errorurl = Http://127.0.0.1:8081/cas-server/error

First of all, from the Web.xml configuration information can be seen, there are three filters responsible for processing the single sign-on process, the first two for the process must be processed by the filter, the last one is my newly added filter, the main function is to initialize user information and permissions. Since the source code interpretation, we must look at the source code. The following is from the CAS client source code to explain the CAS single sign-on client workflow. Then write a separate article on the source code interpretation of CAS single sign-on server.

Authenticationfilter

From single sign-on The first filter begins to interpret, the first filter in the source code is authenticationfilter, because the business requirement has been developed two times for this filter. The source code is to read the initialization parameters from the Web.xml configuration file, which I modified to read the initialization parameters from the properties file. To define the configuration parameters of single sign-on to the properties file, the advantage of this is to unify and manage the initialization configuration parameters at a glance. Source code to go up.

The initialization method of the parent class of the Authenticationfilter, the main task is to obtain the system parameters of a single sign-on from the properties of the Abstractcasfilter. So that we see more clearly, the source code omitted the output of the log.

public void Initconfig () throws Servletexception {
	Properties conf = propertiesutil.getconfigproperties ();
	Setservername (Conf.getproperty ("ServerName", null));
	Setservice (Conf.getproperty ("service", null));
	Setartifactparametername (Conf.getproperty ("Artifactparametername", "Ticket"));
	Setserviceparametername (Conf.getproperty ("Serviceparametername", "service"));
	Setencodeserviceurl (Parseboolean (Conf.getproperty ("Encodeserviceurl", "true"));
	The login error jumps to the URL address
	seterrorurl (Conf.getproperty ("Errorurl", null));
		
	Initialize configuration file (Authenticationfilter Class)
	initinternalconfig (conf);
	Init ();//Initialize
}

The initialization method of the Authenticationfilter. The main task is to obtain the system parameters of single sign-on from properties. So that we see more clearly, the source code omitted the output of the log.

public void Initinternalconfig (Properties conf) throws Servletexception {
	if (!isignoreinitconfiguration ()) {
		Setcasserverloginurl (Conf.getproperty ("Casserverloginurl", null));
		Setrenew (Parseboolean (Conf.getproperty ("Renew", "false"));
		Setgateway (Parseboolean (Conf.getproperty ("Gateway", "false"));

		String Gatewaystorageclass = Conf.getproperty ("Gatewaystorageclass", null);

		if (Gatewaystorageclass = null) return
			;
		try {
			this.gatewaystorage = ((gatewayresolver) Class.forName (Gatewaystorageclass). newinstance ());
		Exception e) {
			this.log.error (E, E);
			throw new Servletexception (e);
		}
	}

Authenticationfilter filtration method.

Public final void Dofilter (final servletrequest servletrequest, final servletresponse servletresponse, final Filterchain Filterchain) throws IOException, Servletexception {final HttpServletRequest request = (httpservletrequest) servletreq
	uest;
	Final HttpServletResponse response = (httpservletresponse) servletresponse;
	Final HttpSession session = Request.getsession (false); Get assertion Final Assertion Assertion = (session!= null) named "_const_cas_assertion_" from session?
	(assertion) Session.getattribute (const_cas_assertion): null;
		If present, the description is already logged in, the filter is processed, and the next filter if (assertion!= null) {Filterchain.dofilter (request, response) is processed;
	Return
	}//Generate serviceurl final String serviceurl = constructserviceurl (request, response); Get parameters from Request ticket (st-1-4hh2s5tzsmgcctodvgcb-cas01.example.org) Final String ticket =
	Commonutils.safegetparameter (Request, Getartifactparametername ());
	Final Boolean wasgatewayed = This.gatewayStorage.hasGatewayedAlready (request, serviceurl); If ticKet is not NULL, this filter is processed and the next filter if (Commonutils.isnotblank (ticket)) | | (wasgatewayed))
		{Filterchain.dofilter (request, response);
	Return

	} this.log.debug ("No ticket and no assertion found");
	Final String Modifiedserviceurl;
		if (This.gateway) {this.log.debug ("setting gateway attribute in session");
	Modifiedserviceurl = this.gatewayStorage.storeGatewayInformation (request, serviceurl);
	else {modifiedserviceurl = serviceurl;
	} if (this.log.isDebugEnabled ()) {this.log.debug ("Constructed service URL:" + modifiedserviceurl); ///Generate redirect URL final String Urltoredirectto = Commonutils.constructredirecturl (This.casserverloginurl,

	Getserviceparametername (), Modifiedserviceurl, This.renew, This.gateway);
	if (this.log.isDebugEnabled ()) {This.log.debug ("redirecting to \" + Urltoredirectto + "\");
//Jump to the login page of CAS server response.sendredirect (Urltoredirectto); }

When we access the application system with single sign-on configured from the browser (http://127.0.0.1:8090/webapp/ Main.do), because the CAS single sign-on client is integrated into the first filter authenticationfilter (regardless of other non single sign-on filters), do the following:

Gets the assertion object named "_const_cas_assertion_" from the session to determine if the assertion exists, and if so, indicates that it is logged in and executes the next filter. If it does not exist, perform step 2nd. Generates Serviceurl (http://127.0.0.1:8090/webapp/main.do), obtains the ticket parameter ticket from request, determines whether the ticket is empty, and executes the next filter if it is not empty. If it is empty, perform step 3rd. Generates a redirection URL (http://127.0.0.1:8081/cas-server/login?service=http://127.0.0.1:8090/webapp/main.do). Jump to a single sign-on server, display the login page, at which time the first filter execution completes.

Ticketvalidationfilter

Abstractticketvalidationfilter filtration method.

Public final void Dofilter (final servletrequest servletrequest, final servletresponse servletresponse, final Filterchain
		Filterchain) throws IOException, servletexception {if (!prefilter (ServletRequest, Servletresponse, FilterChain)) {
	Return
	Final HttpServletRequest request = (httpservletrequest) servletrequest;
	Final HttpServletResponse response = (httpservletresponse) servletresponse;
	Get parameters from Request final String ticket = Commonutils.safegetparameter (Request, Getartifactparametername ()); Ticket is not NULL, verify ticket, otherwise this filter processing completes, processing next filter if (Commonutils.isnotblank (ticket)) {if (this.log.isDebugEnabled ()) {this.
		Log.debug ("Attempting to validate ticket:" + ticket); try {//Validate ticket and produce assertion object, error thrown ticketvalidationexception exception Final assertion assertion = This.ticketvalidator.

			Validate (Ticket, Constructserviceurl (request, response)); if (this.log.isDebugEnabled ()) {This.log.debug ("Successfully authenticated User:" + assertion.getprincipal (). GetName ());
			//request Set Assertion Request.setattribute (const_cas_assertion, assertion);
			Session Settings Assertion if (this.usesession) {request.getsession (). setattribute (const_cas_assertion, assertion);

			Onsuccessfulvalidation (Request, response, assertion);
				if (this.redirectaftervalidation) {this.log.debug ("Redirecting after successful ticket validation.");
				Response.sendredirect (Constructserviceurl (Request, response));
			Return
			The catch (Final Ticketvalidationexception e) {response.setstatus (403);
			This.log.info ("Obtain user authentication information failure:" + e.getmessage ());
			Jump to error page Response.sendredirect (Geterrorurl () + "? Errortype=" + e.getmessage () + "&" + CreateService ());
		Return
}//This filter processing is completed, processing the next filter filterchain.dofilter (request, response); }

Assuming that after the first filter is executed, jump to the login page on the CAS server side, enter the username and password, and verify the pass. The CAS server side generates ticket and ticket as a parameter for a rerun to the application system (http://127.0.0.1:8090/webapp/main.do?ticket= st-1-4hh2s5tzsmgcctodvgcb-cas01.example.org). At this point the first filter authenticationfilter, because there are ticket parameters, go to the second filter ticketvalidationfilter, do the following: Get the ticket parameter from request, If ticket is empty, continue with the next filter. If the parameter is not NULL, verify the legality of the ticket parameter. Verify that the Ticket,ticketvalidationfilter Validate method accesses the CAS server side through HttpClient (http://127.0.0.1:8081/cas-server/ servicevalidate?ticket=st-1-4hh2s5tzsmgcctodvgcb-cas01.example.org&service=http://127.0.0.1:8090/webapp/ Main.do) verifies that the ticket is correct and returns the assertion object. If validation fails, throws an exception and jumps to the error page. If the validation succeeds, the session saves the assertion object with the name "_const_cas_assertion_" and continues processing the next filter. Initloginuserfilter Initloginuserfilter filtration method.

Public final void Dofilter (final servletrequest servletrequest, final
		servletresponse Servletresponse, final Filterchain Filterchain)
		throws IOException, servletexception {
	
	try {
		//plus its own applied logic, such as constructing user information and permissions, etc.
		/ ...
		
		This filter is processed and processed next filter
		filterchain.dofilter (request, response);
		return;
	} catch (Exception e) {
		//Jump to error page
		Res.sendredirect (geterrorurl () + "? Errortype=" + e.getmessage () + "&" + Crea Teservice ());
	}

This filter is my new addition to the filter to meet the special operations of the application system. When this filter is reached, the CAS server is logged in successfully, and the filter initializes the information required by the application system (user profile and permissions, etc.). When the operation is completed, the first page of the application system is displayed. If an exception occurs, jump to the error page.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.