Web-sso-client

Source: Internet
Author: User
Tags throwable

3.2.2 Web application source code parsing with SSO capability to implement Web-sso functionality, only the authentication service is not enough. Obviously, for multiple applications to have single sign-on functionality, each application itself needs to be mated: handing its own authentication service to a unified authentication service,-ssoauth. The various methods provided in the Ssoauth service are for each Web application that joins SSO. In general, Web applications require the functionality of SSO and should be invoked through the following interactive process to invoke the authentication service provided by the Identity authentication Service:
    • Every URL that needs security in the Web app needs a security check before access, and if it finds no sign-in (no cookies are found after authentication), redirect to login.jsp in Ssoauth to log in.
    • Once the login is successful, the system will automatically set a cookie to your browser to prove that you have logged in.
    • When you revisit the URL that the app needs to protect, the system still has to perform security checks, but this time the system is able to find the appropriate cookie.
    • With this cookie, there is no proof that you have access. Your cookie may be invalid in these cases because you may have already logout, or the cookie has expired, or the authentication service has been re-established. The app gets this cookie, and it needs to invoke the authentication service to determine if the cookie is really valid and who the current cookie corresponds to.
    • If the cookie is successful, the user is allowed to access the currently requested resource.
These features can be implemented in a number of ways:
    The
    • joins the authenticated service in each resource being accessed (JSP or servlet) to obtain a cookie and to determine whether the current user has logged in. But no one can use:-) in this stupid way. The
    • can use a controller to write all of the functions into a servlet, and then map the URLs to all the collection of URLs that need to be protected (such as *.jsp,/security/*, etc.) when the URL is mapped. This method can be used, however, its disadvantage is that it cannot be reused. Deploy an identical servlet in each application. The
    • filter is the better method. The Java EE container, which conforms to Servlet2.3, has the ability to deploy filter. (Use of filter can refer to Javawolrd's article http://www.javaworld.com/javaworld/jw-06-2001/ jw-0622-filters.html) filter is a well-modular, reusable programming API that is suitable for SSO. This example uses a filter to perform the above functions.
 package sso; import java.io.*;import java.net.*;import java.util.*;import java.text.*;import Javax.servlet.*;import Javax.servlet.http.*;import Javax.servlet.*;import Org.apache.commons.httpclient.*;import Org.apache.commons.httpclient.methods.getmethod; public class Ssofilter implements Filter {     private filterconfig filterconfig = null;    private String cookiename= "WangYuDesktopSSOID ";     private String ssoserviceurl= " Http://wangyu.prc.sun.com:8080/SSOAuth/SSOAuth ";     private String ssologinpage= "http://wangyu.prc.sun.com:8080/SSOAuth/login.jsp";        public void init (filterconfig filterconfig) {          this.filterconfig = Filterconfig;        if ( Filterconfig! = null) {            if (Debug) {                log ("SSOFilter:I Nitializing filter ");            }         }                cookiename = Filterconfig.getinitparameter ("CookieName");         ssoserviceurl = Filterconfig.getinitparameter ("Ssoserviceurl");         ssologinpage = Filterconfig.getinitparameter ("Ssologinpage");    }  ...  } The initialization of the source code above has two points to be explained: First, there are two parameters that need to be configured Ssoserviceurl and Ssologinpage. Because the current web application is likely to be not on the same machine as the Authentication Service (Ssoauth), this filter needs to know the URL of the authentication Service deployment in order to invoke its service. Another point is that because the service invocation of authentication is to be invoked through the HTTP protocol (in this case, the reader can design its own identity service, use other invocation protocols, such as RMI or SOAP, etc.), All the authors cite the Apache Commons Toolkit (more information about accessing apache  's website http://jakarta.apache.org/commons/index.html), where the "httpclient" Can greatly simplify the HTTP tuningThe program used. Here's a look at the main method of filter doFilter ():p ublic void DoFilter (ServletRequest req, servletresponse Res, filterchain chain) throws IOException, servletexception {        if (Debug) log ("SSOFilter:doFilter ( );         httpservletrequest request = (httpservletrequest) req;         httpservletresponse response = (httpservletresponse) res;         string result= "Failed";         String URL = Request.getrequesturl (). toString ();         string qstring = Request.getquerystring ();         if (qstring = = null) qstring = "";          //Check if the head of the HTTP request is required cookie         string cookievalue = "";         javax.servlet.http. cookie[] diskcookies = Request.getcookies ();         if (diskCookies! = null) {            for (int i = 0; i< diskCookies.length; i+ +) {                if ( Diskcookies[i].getname (). Equals (CookieName)) {                     cookievalue = Diskcookies[i].getvalue ();                       //if a corresponding cookie is found, it is effective                      result = Ssoservice (cookievalue);       &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;IF (Debug) log ("Found cookies !");                }             }        }         if (Result.equals ("failed")) {//validation failed or no cookie found, login required              response.sendredirect (SSOLoginPage+ "? goto=" +url);         } else if (Qstring.indexof ("logout") > 1) {//logout Services    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;IF (Debug) log ("Logout action!");             logoutservice (CookieValue);             response.sendredirect (SSOLoginPage+ "? goto=" + URL);         } else {//Efficacy        Success      &nbSp;request.setattribute ("Ssouser", result);             throwable problem = Null;            try {                 Chain.dofilter (req, res);             } catch (Throwable t) {                 problem = t;                 t.printstacktrace ();             }                   if (problem! = null) {                 if (Problem instanceof ServletException) throw ( SerVletexception) problem;                 if (Problem instanceof IOException) throw (IOException) problem;                 sendprocessingerror (problem, RES);             }        } The logic of the       }dofilter () method is also very simple, when the request is received, the first to look for the existence of the expected cookie value, if found, will call Ssoservice ( Cookievalue) to check the validity of this cookie. If the cookie is not successful or the cookie does not exist at all, it will be transferred directly to the login interface to allow the user to log in, and if the cookie is successful, there will be no blocking to allow this request to continue. In the configuration file, one of the following nodes represents the URL mapping relationship for this filter: only all JSP requests are blocked. <filter-mapping><filter-name>ssofilter</filter-name><url-pattern>*.jsp</url-pattern ></filter-mapping>  Here are a few key functions to note:     private string Ssoservice (string Cookievalue) throws IOException {        string AuthAction = "Action=authcookie&cookiename=";         httpclient HttpClient = new HttpClient ();         getmethod httpget = new GetMethod ( Ssoserviceurl+authaction+cookievalue);         try {              httpclient.executemethod (HttpGet);             string result = Httpget.getresponsebodyasstring ();             return result;         } finally {             Httpget.releaseconnection ();        }    }        private void Logoutservice (String cookievalue) throws IOException {      &Nbsp;  string authaction = "? action=logout&cookiename=";         httpclient HttpClient = new HttpClient ();         getmethod HttpGet = New GetMethod (ssoserviceurl+authaction+cookievalue);         try {             httpclient.executemethod (HttpGet);             httpget.getresponsebodyasstring ();         } finally {             httpget.releaseconnection ();        }   &NBSP;&NBSP: These two functions are primarily used by httpclient in Apache to access the authentication services provided by Ssoauth to perform the functions of the validated cookie and logout. The other functions are simple, and many of them are automatically generated for me by my IDE (NetBeans).

Web-sso-client

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.