Web-sso Code Analysis

Source: Internet
Author: User
Tags map class

3.2 Web-sso Code explanation 3.2.1 Authentication Service Code parsing Web-sso source can be downloaded from the website address http://gceclub.sun.com.cn/wangyu/web-sso/websso_src.zip. The Identity authentication Service is a standard Web application, including a servlet named Ssoauth, a login.jsp file, and a failed.html. Almost all of the services for identity authentication are implemented by the Ssoauth servlet. Login.jsp is used to display the page that is logged on (if the user is not logged in), failed.html is used to display information about the login failure (if the user's user name and password are not the same as in the information database). The Ssoauth code is shown in the following list, the structure is very simple, first look at the main part of the servlet: package Desktopsso; import java.io.*;import Java.net.*;import Java.text.*;import Java.util.*;import Java.util.concurrent.*; import Javax.servlet.*;import Javax.servlet.http.*;  public class Ssoauth extends HttpServlet {        static private Concurrentmap accounts;    static private Concurrentmap SSOIDs;     string cookiename= "wangyudesktopssoid";     string domainname;        public void init (servletconfig config) throws Servletexception {         super.init (config);          domainname= config.getinitparameter ("domainname");         cookiename = Config.getinitparameter ("CookieName");         ssoids = new Concurrenthashmap ();         accounts=new Concurrenthashmap ();         accounts.put ("Wangyu", "Wangyu");         accounts.put ("Paul", "Paul");         accounts.put ("Carol", "Carol");     }     protected void ProcessRequest (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {         printwriter out = Response.getwriter ();         string action = request.getparameter ("action");         StriNg result= "failed";         if (Action==null) {             handlerfromlogin (Request,response);         } else if (Action.equals ("Authcookie")) {             string MyCookie = Request.getparameter ("CookieName");             if (MyCookie! = null)  result = Authcookie (MyCookie);             out.print (Result);             out.close ();         } else if ( Action.equals ("Authuser")) {           result= AUTHNAMEANDPASSWD (Request,response);             Out.print (result);              out.close ();         } else if (action.equals ("logout")) {             string MyCookie = Request.getparameter ("CookieName");             logout (MyCookie);             out.close ();         }    }   }  from the code it is easy to see that Ssoauth is a simple servlet. There are two static member variables: Accounts and Ssoids, these two member variables use the JDK1.5 thread-safe Map class: Concurrentmap, so this sample must be JDK1.5 to run. Accounts is used to store user names and passwords, and in init () you can see that I have added three legitimate users to the system. In practice, accounts should be obtained in the database or LDAP, for simplicity, in this example I used Concurrentmap to create three users in memory with a program. Ssoids, however, preserves the corresponding relationship between the cookie and the user name generated after the user's successful login. Its function is obvious: When the user successfully login, again access to other systems, in order to identify the user request for the validity of the cookie, need to ssoids to check if such a mapping relationship exists.   in the main request handling method ProcessRequest (), it is clear to see all the features of Ssoauth
    1. If the user has not logged in, it is the first time to log in to the system and will be redirected to the login.jsp page (which will explain how to jump later). After the user has provided the user name and password, it will be validated using the Handlerfromlogin () method.
    2. If the user has logged in to the system and then accesses another application, it is not necessary to log in again. Because the browser sends the cookie and request that was generated at the first logon. The validity of the validated cookie is one of the main functions of Ssoauth. The
    3. Ssoauth also has the ability to directly work out the validation requests for usernames and passwords that are not login.jsp pages. This feature is for SSO for non-Web applications, which is used in desktop SSO later. The
    4. Ssoauth also provides logout services.
  Take a look at some of the main function functions:  private void Handlerfromlogin (HttpServletRequest request, httpservletresponse response) Throws Servletexception, IOException {        string username = Request.getparameter ("username");         string password = Request.getparameter ("password");         string pass = (String) Accounts.get (username);         if ((pass==null) | | (!pass.equals (password)))             getservletcontext (). Getrequestdispatcher ("/failed.html"). Forward (request, response);         else {            string GotoURL = Request.getparameter ("goto");             string NewID = Createuid ();       &nbSp;     ssoids.put (NewID, username);             cookie Wangyu = new Cookie (cookiename, NewID);             wangyu.setdomain (domainname);             wangyu.setmaxage (60000);             wangyu.setvalue (NewID);             Wangyu.setpath ("/");             response.addcookie (Wangyu);             system.out.println ("Login Success, goto back URL: "+ gotourl);             if ( Gotourl = null) {                 printwriter out = response.getwriter ();                 Response.sendredirect (Gotourl);                 out.close ();             }         }      }handlerfromlogin () This method is used to process login requests from login.jsp. The logic is simple: Compare the user name and password entered by the user with a predefined set of users (stored in accounts), if the user name or password does not match, Returns the login Failed page (failed.html), if the login is successful, you need to create a new ID for the user's current session, and the ID and User Name Mapping relationship to Ssoids, and finally set this ID to the browser can save the cookie value. When the login is successful, which page does the browser go to? Let's review how we use the Identity authentication service. In general, we do not directly access any URL to the identity service, including login.jsp. Identity services are used to protect other app services, and users typically access a URL for a ssoauth-protected web App, and the current app will find that the current user is not logged in, forcing the page to turn to the Ssoauth login.jsp, allowing the user to log in. If the login succeeds, the user's browser should be automatically directed to the URL that the user originally wanted to access. In Handlerfromlogin () This method, we receive the "goto" parameter to save the URL that the user originally visited, and then redirect to this page after success. Another thing to note is that I used a setmaxage (6000) method when setting up a cookie. This method is used to set the lifetime of the cookie, in seconds. If you do not use this method or the parameterIf the number is negative, the cookie will expire when the browser is closed. Here I give a very large value (1000 minutes), causing the behavior is: when you close the browser (or shut down), the next time you open a browser to access the application, as long as within 1000 minutes, you do not need to log in again. What I do is the following features required in desktop SSO to be covered. Other methods are simpler, and there's not much to explain here.  

Web-sso Code Analysis

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.