java--for Single Sign-on

Source: Internet
Author: User

java--for Single Sign-on

1what is a single sign-onSingle Sign-on, referred to as  sso, is one of the more popular solutions for enterprise business integration. The definition of SSO is that in multiple application systems, users can access all trusted applications with only one login. Larger enterprises, generally have a lot of business support system to provide it with the corresponding management and IT services. For example, the financial system provides financial management, calculation and Reporting Services for financial personnel, and personnel systems provide maintenance services to personnel departments throughout the company, and various business systems provide different services to different businesses within the company. The purpose of these systems is to allow computers to carry out complex and tedious computations, instead of manual labor, to improve work efficiency and quality. These different systems are often built at different times and run on different platforms, perhaps developed by different vendors, using a variety of different technologies and standards. If, for example, a well-known IT company in the country (the name of the hidden), there are more than 60 business systems, including two different versions of SAP ERP system, 12 different types and versions of the database system, 8 different types and versions of the operating system, and the use of 3 different firewall technology, There are dozens of different protocols and standards that are incompatible with each other, do you believe? Do not doubt that this is a very common situation. Each application system has been running for several years and will become part of an irreplaceable enterprise IT architecture, as shown in. With the development of enterprises, the number of business systems is constantly increasing, the old system can not be easily replaced, which will bring a lot of overhead. One is the overhead of management and the increasing number of systems that need to be maintained. The data of many systems is redundant and duplicated, and the inconsistency of data will put a lot of pressure on the management work. There is also a growing correlation between business and business, such as the company's billing and financial systems, and the inevitable close relationship between the financial system and the personnel system. In order to reduce the consumption of management and maximize the reuse of existing investment systems, many enterprises are doing enterprise application integration (EAI). Enterprise application integration can be carried out at different levels: "Data centralization" at the data storage level, "Common data exchange Platform" at the transport level, "business process integration" at the application level, and "Common Enterprise Portal" on the user interface, etc. In fact, it is becoming more and more important to use one level of integration, that is, "Identity authentication" integration, that is, "single sign-on." In general, each individual system will have its own security system and identity authentication system. Integration before, into each system need to login, this situation not only to the management has brought great difficulties, in the security also buried a major hidden trouble. Here are some of the statistics displayed by some of the well-known survey companies:
    • Users spend an average of five minutes per day on authentication tasks - Source: IDS
    • Frequent IT users have an average of eight passwords - Source: NTA Monitor Password Survey
    • 49% people write down their passwords, and 67% seldom change them.
    • An identity theft event occurs per second hour - Source: National Small Business Travel ASSOC
    • Global fraud loss of about 12B per year- Source: Comm fraud Control Assoc
    • By the year, the identity management market will grow exponentially to $4.5b- Source: IDS
With "Single Sign-on" consolidation, only one login is required to enter multiple systems without having to log back in, which not only leads to a better user experience, but more importantly reduces the risk of security and the consumption of management. Take a look at the following statistical data:
    • Improve IT efficiency: Save $70k per user for each of our managed users
    • Help desk calls reduce at least 1/3, for 10K employees of the company, each year can save $ per user, or the total $648k
    • Productivity gains: Each new employee can save $1k, and every old employee can save $350 . data Source: Giga
    • ROI return:7.5 to six months? Source: Gartner
Also, using single sign-on is one of the requirements of the SOA era. In the service-oriented architecture, the communication between the service and the service, between the program and the program exists, and the security authentication between the services is one of the difficulties in SOA application, so the system system of "single sign-on" can greatly simplify the security problem of SOA and improve the efficiency of cooperation between services.2the technology realization mechanism of single point landingWith the popularity of SSO technology, SSO products are flying all over the sky. All well-known software vendors provide the appropriate solutions. I do not want to introduce my company (Sun Microsystems) products here, but to analyze the SSO technology itself, and provide a way to develop this type of product and a simple demonstration.The Summer Palace is a famous tourist attraction in Beijing, and it is also a place I often visit. There are many independent attractions inside the Summer Palace, such as "Suzhou Street", "Buddhist Incense" and "Tak and Yuan", which can be bought separately at the entrance of various attractions. Many tourists need to play all the German attractions, this way of buying tickets is very inconvenient, need to stand in front of each scenic spot to buy tickets, wallets taken out, easy to lose, very insecure. So the vast majority of tourists choose to buy a ticket at the gate (also called the package), you can play all the sights and no need to re-buy tickets. All they need to do is show the tickets they just bought at the entrance of each attraction and be allowed to enter each individual attraction. The same as the mechanism of single sign-on, as shown, when the user first access to the application System 1, because not yet logged in, will be directed to the authentication system to log in (1), according to user-provided login information, authentication system for identity verification, if through validation, Should be returned to the user a certified credential--ticket (2); When the user accesses another application (3,5) will take this ticket, as the credentials of their own authentication, the application system to accept the request will ticket sent to the authentication system for validation, Check the legality of the ticket (4,6). If tested, the user can access application System 2 and application 3 without having to log in again. As you can see from the above view, to implement SSO, you need the following key features:
    • All application systems share an identity authentication system.
      A unified authentication system is one of the prerequisites for SSO. The main function of the authentication system is to compare the user's login information with the user database, to authenticate the users, and after the successful authentication, the authentication system should generate a unified certification mark (ticket) and return it to the user. In addition, the certification system should be ticket to determine its effectiveness.
    • All application systems can identify and extract ticket information
      To enable SSO functionality so that users log on only once, the application must be able to identify the users who have already logged in. Application system should be able to identify and extract the ticket, through the communication with the authentication system, can automatically determine whether the current user has logged in, thus completing the single sign-on function.
The above feature is just a very simple SSO architecture, and in reality SSO has a more complex structure. There are two points to note:
    • A single user information database is not required, and many systems cannot store all user information centrally, and should allow user information to be placed in different stores as shown in. In fact, as long as the unified authentication system, unified ticket production and validation, no matter where the user information is stored, can achieve single sign-on.
    • A unified authentication system is not to say that only a single authentication server, as shown, the entire system can exist more than two authentication servers, these servers can even be different products. Authentication server through the standard communication protocol, mutual exchange of authentication information, you can complete a higher level of single sign-on. For example, when the user accesses the application System 1 o'clock, is authenticated by the first authentication server, obtains the ticket which this server produces. When he accesses the application System 4, authentication server 2 can recognize that this ticket is generated by the first server, through the authentication server between the standard communication protocol (such as SAML) to Exchange authentication information, still can complete the function of SSO.
3 Web-ssothe implementationWith the rapid development of the Internet, Web applications almost dominate most software applications, so Web-sso is the most popular in SSO applications. Web-sso has its own characteristics and advantages, it is more simple and easy to implement. Many commercial software and open source software have the implementation of Web-sso. It is worth mentioning that opensso  (https://opensso.dev.java.net), for the implementation of Java Web-sso provide architectural guidance and service guide, for the user to implement the Web-sso provides a theoretical basis and implementation of the method. Why is it easier to say that Web-sso is easy to implement? This is determined by the characteristics of the Web application itself. As we all know, a Web protocol (that is, HTTP) is a stateless protocol. A Web application consists of a number of web pages, each of which has a unique URL to define. The user enters the URL of the page in the address bar of the browser, and the browser sends the request to the Web server. For example, the browser sends two requests to the Web server and requests two pages. The requests for the two pages were using two separate HTTP connections respectively. The so-called stateless protocol is where the browser and Web server close the connection channel after the first request completes and reestablish the connection at the second request. The Web server does not distinguish which client the request is from, and all requests are treated equally, and are separate connections. This way is greatly different from the traditional (Client/server) C/s structure, in such applications, the client and the server side will establish a long-time dedicated connection channel. It is because of the stateless nature that every connection resource can be quickly reused by other clients, and a Web server can serve tens of thousands of clients at the same time. But our usual application is stateful. Without mentioning SSO between different applications, you also need to save the user's login identity information in the same application. For example, the user logged on to page 1, but also mentioned that each client request is a separate connection, when the customer visited page 2 again, how to tell the Web server, the customer has just logged in? There is a convention between the browser and the server: Use cookie technology to maintain the state of the app. A cookie is a string that can be set by a Web server and can be saved in a browser. As shown, when the browser accesses page 1 o'clock, the Web server sets a cookie and returns the cookie and page 11 to the browser, which is saved after the browser receives the cookie, and when it accesses page 2, the cookie is also taken. When the Web server receives the request, it can read the value of the cookie, and it can judge and restore some users ' information status according to the content of the cookie value.Web-sso can complete the storage of user login information by the end of the cookie, combine the cookie in the browser with the ticket above and complete the SSO function.   In order to complete a simple SSO feature, a two-part collaboration is required:
      1. A unified identity authentication service.
      2. Modify the Web application so that each application is authenticated through this unified authentication service.

 PackageCom.ll.singlelogin; Importjavax.servlet.http.*; ImportJava.util.*;  Public classSingleloginImplementsHttpsessionlistener {//Saving mappings for SessionID and username    Private StaticHashMap Husername =NewHashMap (); /**here are the methods implemented in Httpsessionlistener **/       Public voidsessioncreated (httpsessionevent se) {} Public voidsessiondestroyed (httpsessionevent se) {husername.remove (Se.getsession (). GetId ()); }          /*** isalreadyenter-is used to determine if the user is logged in and the appropriate method of handling * *@paramsUserName * string-logged in User name *@returnboolean-flag that the user has logged in*/       Public Static BooleanIsalreadyenter (HttpSession session, String sUserName) {BooleanFlag =false; //If the user has logged in, the last logged-on user is dropped (depending on whether the username is in husername)        if(Husername.containsvalue (sUserName)) {flag=true; //traverse the original husername, delete the original user name corresponding to the SessionID (that is, delete the original SessionID and username)Iterator iter =Husername.entryset (). iterator ();  while(Iter.hasnext ()) {Map.entry Entry=(Map.entry) iter.next (); Object Key=Entry.getkey (); Object Val=Entry.getvalue (); if((String) val). Equals (sUserName)) {husername.remove (key); }              }              //Add the current SessionID and usernameHusername.put (Session.getid (), sUserName); System.out.println ("Husername =" +husername); } Else{//If the user is not logged in, add the current SessionID and username directlyFlag =false;              Husername.put (Session.getid (), sUserName); System.out.println ("Husername =" +husername); }          returnFlag; }          /*** isonline-is used to determine if the user is online * *@paramSession * httpsession-Login user name *@returnboolean-Whether the user is online logo*/       Public Static BooleanIsOnline (HttpSession session) {BooleanFlag =true; if(Husername.containskey (Session.getid ())) {flag=true; } Else{flag=false; }          returnFlag; }  } 

Web. XML deployed under/app/web-inf

<?xml   version= "1.0"   encoding= "iso-8859-1"?>     <! DOCTYPE   web-app   public "-//sun   Microsystems,   inc.//dtd   web   Application   2.3//en "   " Http://java.sun.com/j2ee/dtds/web-app_2.3.dtd ">     <web-app>     <listener>   <listener-class>   com.inspirer.dbmp.SessionListener   </listener-class>   </listener>     


Application section
1. During your login verification, call Sessionlistener.isalreadyenter (Session, "admin")
The user name can be determined whether the user is logged in, and the last logged on user can drop the line
2. Other pages call Sessionlistener.isonline (session) to determine if the user is online.

Transferred from: http://blog.csdn.net/java_freshman01/article/details/7202776

Use the SSH architecture to illustrate:
1. Create a login management class Loginmanager
2. Define a collection in Loginmanager to manage the logged-in user.
3. In spring, configure Loginmanager as a singleton
4. If you are using a custom user management class, Name this class UserContext (representing the context of user authorization) for convenience.
5. If you are not using a custom user management class, use the session directly.
6. In the Login authorization object, check whether the user is a legitimate user, and if it is a legitimate user, find whether the user is online in the Loginmanager collection, and if not, add the user to the collection.
7. Processing strategy One: If the user is already online, then take the new login user's session and invalidate it, which will prevent the new logged-in user from logging in.
8. Processing Strategy Two: If the user is already online, remove the session of the online user, invalidate it, and then add the new login user to the Loginmanager collection. The logged-on user cannot perform a permission operation and can only log on again.

1. Applicationcontext.xml
<BeanID= "Loginmanager"class= "Loginmanager"Scope= "Singleton" /><BeanID= "Action"class= "Loginaction"scopt= "Prototype" >    < Propertyname= "Laginmanager"ref= "Loginmanager" /></Bean>

2. Loginmanager.java

Collection<session>sessions; PublicSession Login (session session) { for(Session s:sessions) {if(S and session are the same user) policy one:returnSession Strategy two: {Sessions.add (session);//these two rows in the loop manipulate the collection class to throw an exceptionSessions.remove (s);//here is a simple demonstration code, which should be processed out of loop in the actual code.                returns;    }} sessions.add (session); return NULL;}

3. Loginaction.java

Loginmanager Loginmanager;  Public throws Exception {    take session    Check user name, password     if  (is a legitimate user)        {= loginmanager.login (session);         if (null! =session) Session.invalidate ();}    }

4. If you have customized the UserContext, you can change the collection to collection<usercontext> users;

5. Usercontext.java

Session session; Session getsession () {    returnthis. session;} Boolean Login (string userName, string password) {    Access database, check user name password     return  is legal;} Boolean Sameuser (UserContext UC) {    return uc.userName.equals (this. userName);}

6. Modify Loginmanager.java

Collection<usercontext>users; PublicUserContext Login (UserContext user) { for(UserContext uc:users) {if(Uc.sameuser (user)) policy one:returnUser Policy two: {users.add (user); //these two rows in the loop manipulate the collection class to throw an exceptionUsers.remove (UC);//here is a simple demonstration code, which should be processed out of loop in the actual code.            returnUC;    }} users.add (user); return NULL;}

7. Modify Loginaction.java

 Public throws Exception {    //  can also take session within UserContext.     New  UserContext ();    User.setsession (session);     if (User.login (userName, password)) {        = loginmanager.login (user);         if (null! =UC) uc.getsession (). invalidate ();}    }

java--for Single Sign-on

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.