Example of single-point login implementation solution for PHP

Source: Internet
Author: User
Tags error status code
Abstract: This article mainly introduces the use of webservice, session, cookie technology to analyze and design a universal single sign-on system. The specific implementation language is PHP. Single Sign-On (single sign-on) is an important part of comprehensive user processing for enterprises and network businesses. The English name is SingleSignOn (SSO for short. The SSO definition is that in multiple application systems, users can access all Abstract:

This article mainly introduces the use of webservice, session, cookie technology to analyze and design a universal single sign-on system. The specific implementation language is PHP. Single Sign On (SSO) is an important part of the comprehensive processing of network business users. The SSO definition is that in multiple application systems, users only need to log on once to access all mutually trusted application systems.


If you have used the ucenter full-site logon method, you should know that this is a typical observer solution. As a subject, the user Center registers and deletes its observer in the background of the ucenter. Each sub-application site corresponds to an observer. Every time you log on to the user Center, the js script is triggered to call back the w3c standard sub-station logon interface (api/uc. php ).

I think there are two main disadvantages of this method: 1. when the number of sub-sites is too large, the number of callback interfaces increases accordingly. in terms of the number of sub-sites distributed, how to control the login efficiency is not too low and difficult to grasp; 2. when a sub-station callback interface encounters a problem, the default logon process gets stuck (the execution time of the logon program can be limited, but the callback interface of the sub-station after the sub-station fails to be called.

Based on the above problems, I designed another single sign-on system in the actual development process.

1. logon principles

Technical implementation mechanism of single sign-on: when a user accesses application system 1 for the first time, the user is directed to the authentication system for logon because the user has not logged on. based on the login information provided by the user, the authentication system performs identity verification. if the authentication succeeds, a ticket credential should be returned to the user. when the user accesses another application, the ticket will be taken, as your authentication credential, the application system sends the ticket to the authentication system for verification after receiving the request to check the validity of the ticket. After verification, you can access application system 2 and Application System 3 without having to log on again.

We can see that the following main functions are required to implement SSO:

A) all application systems share an identity authentication system;

B) all application systems can identify and extract ticket information;

C) the application system can identify users who have logged on, and automatically determine whether the current user has logged on to the system to complete the single sign on function.

Based on the above basic principles, I have designed a single sign-on system program in php language, which has been put into operation by generating servers. The system program uses the unique session id of the whole system as the media to obtain the full site information of the current online user (login status information and other user full site information to be processed ).

II. process description:

Login process:

1. log on to a website for the first time:

A) the user enters the user name and password and sends a logon request to the user verification center.

B) currently logged on to the site. the user verification center verifies the validity of the user name and password through the webservice request. If the verification succeeds, a ticket is generated to identify the user of the current session, and the site identifier of the current sub-site is recorded in the user Center.

C) return the obtained user data and ticket to the sub-site. If the verification fails, the corresponding error status code is returned.

D) according to the results returned by the webservice request in the previous step, the current sub-station logs in to the user. if the status code indicates that the request is successful, the current site saves ticket through the cookie on this site, this site also records the user's logon status. The status code indicates that the logon fails.

2. log on to another sub-account:

A) verify the user's logon status through the site cookie or session: if the verification succeeds, the user enters the normal site processing program; otherwise, the user Center verifies the user's logon status (send ticket to the user verification center ), if the verification succeeds, the returned user information is logged on locally. Otherwise, the user is not logged on.

Logout process

A) the current logout site clears the logon status of the user site and the unique random id of the local user site

B) use the webservice interface to clear the unique random id of the whole site. The webservice interface will return and log out the javascript code of other logged-on sub-sites. this code is output on this site.

C) access the W3C standard logout script of the corresponding site using js code

III. code description:

The code involved in this article has been packaged and uploaded. if you are interested, click download at the last download link of this article.

1. login process:

The user must call the UClientSSO: loginSSO () method for the first sub-site to log on from the browser. This method returns the unique random id of the whole site to identify the user. The random id is saved in UClientSSO: loginSSO () through the cookie on this site. that is, the sub-site retains the user's login id stub on this site.

A) UClientSSO: loginSSO () method:

 $ Username, 'password' => $ alreadyEnc? Trim ($ password): self: simpleEncPass (trim ($ password), 'IP' => self: onlineip (), 'siteflag' => self :: $ site, 'member' => $ remember); $ _ params ['checksum'] = self: _ getCheckSum ($ _ params ['username']. $ _ params ['password']. $ _ params ['IP']. $ _ params ['siteflag']. $ _ params ['Remember ']); // 2. call the webservice interface to log on. // $ aRet = self: _ callSoap ('loginucenter', $ _ params); if (intval ($ aRet ['resultflag'])> 0 & & $ ARet ['sessid ']) {// successfully logged on // set the local session idself: _ setLocalSid ($ aRet ['sessid']); // Set the user Center's unified session id script path self: $ _ synloginScript = urldecode ($ aRet ['script']); $ ret = $ aRet ['userinfo'];} else {$ ret ['status'] = $ aRet ['resultflag'];} return $ ret ;} // end of function // B) the webservice program of the user verification center. after receiving the login verification request, it calls the UCenter: loginUCenter () method to process the login request. /*** User Authentication Center login user processing ** @ param string $ username * @ param string $ password * @ param string $ ip * @ param string $ checksum * @ return array * /static public function loginUCenter ($ username, $ password, $ ip, $ siteFlag, $ remember = false) {self: _ init (); session_start (); $ ret = array (); $ arr_login_res = login_user ($ username, $ password, $ ip); $ res_login = $ arr_login_res ['status']; // $ ret ['resultflag'] = $ res_login; if ($ r Es_login <1) {// login failed} else {// login successful $ _ SESSION [self ::$ _ ucSessKey] = $ arr_login_res; $ _ SESSION [self :: $ _ ucSessKey] ['Salt'] = self: _ getUserPassSalt ($ _ SESSION [self ::$ _ ucSessKey] ['username'], $ _ SESSION [self :: $ _ ucSessKey] ['password']); $ ret ['userinfo'] = $ _ SESSION [self ::$ _ ucSessKey]; $ ret ['sessid '] = session_id (); // generates a unique session id for the entire site, as the ticket full-site access // call back the login interface of the Cooperation Center station (set the unified session id of the user Center) // self: _ createCoSitesInfo (); $ Uinfo = array (); $ _ timestamp = time (); $ _ rawCode = array ('action' => 'setsid ', 'Sid '=> $ ret ['sessid'], 'Time' => $ _ timestamp,); if ($ remember) {$ uinfo = array ('member' => 1, 'username' => $ username, 'password' => $ password );} $ ret ['script'] = ''; $ _ rawStr = http_build_query (array_merge ($ _ rawCode, $ uinfo )); /// set the script address for the global cookie of the partner site // foreach (array) self: $ _ coSitesInfo as $ _ siteInfo) {$ _ code = sel F: authcode ($ _ rawStr, 'encoding', $ _ siteInfo ['key']); $ _ src = $ _ siteInfo ['URL']. '? Code = '. $ _ code. '& time = '. $ _ timestamp; $ ret ['script']. = urlencode ('');} // Remember that you have logged on to the U. S.. // self: registerLoggedSite ($ siteFlag, $ ret ['sessid ']); unset ($ ret ['userinfo'] ['Salt']);} return $ ret;}?>

2. after successfully logging on to the site, perform local user login, and then verify that the user logs on only locally. (Set local access to user status information to close the browser and exit)

3. when detecting the user's login status, call the local verification process first. if the local verification fails, call the UClientSSO: checkUserLogin () method to check the user's login status in the user Center.

A) UClientSSO: The checkUserLogin () method is as follows:

 $ _ SessId, 'siteflag' => self: $ site, 'checksum' => md5 ($ _ sessId. self: $ site. self: $ _ mcComunicationKey); $ aRet = self: _ callSoap ('getonlineuser', $ _ params); if (intval ($ aRet ['resultflag'])> 0) {// $ ret = $ aRet ['userinfo'];} else {$ ret ['status'] = $ aRet ['resultflag'];} return $ ret;} B) the webservice program of the user verification center. after receiving the login check request, call the UCenter: getOnlineUser () method to process the login request: [php]/*** obtain the user email Currently logged on based on the sid Information ** @ param string $ sessId-unique session id of the whole site, which is used as ticket * @ return array * // *** according to sid, obtain the information of the currently logged-on user ** @ param string $ sessId-unique session id of the whole site, which is used as ticket * @ return array */static public function getOnlineUser ($ sessId, $ siteFlag) {self: _ init (); session_id (trim ($ sessId); session_start (); $ ret = array (); $ _ userinfo = $ _ SESSION [self :: $ _ ucSessKey]; if (isset ($ _ userinfo ['username']) & isset ($ _ userinfo [' Password ']) & self: _ getUserPassSalt ($ _ userinfo ['username'], $ _ userinfo ['password']) {$ ret ['resultflag'] = "1"; $ ret ['userinfo'] = $ _ userinfo; self: registerLoggedSite ($ siteFlag, $ sessId ); // Remember that you have logged on to the unset ($ ret ['userinfo'] ['Salt']);} else {$ ret ['resultflag'] = "0 ";} return ($ ret) ;}?>

4. call the UClientSSO: logoutSSO () method when logging out at a single point. After the call is successful, if you need to log out from another logged-on site immediately, call the UClientSSO: getSynloginScript () method to obtain the W3C standard script and output it on the page.

A) UClientSSO: logoutSSO () method:

 $ _ SessId, 'siteflag' => self: $ site, 'checksum' => md5 ($ _ sessId. self: $ site. self: $ _ mcComunicationKey); $ aRet = self: _ callSoap ('logoutucenter', $ _ params); if (intval ($ aRet ['resultflag'])> 0) {// successfully logged out self ::_ removeLocalSid (); // removed the sid stub self :: $ _ synlogoutScript = urldecode ($ aRet ['script']); $ ret = 1;} else {$ ret = $ aRet ['resultflag'];} return intval ($ ret);} [/php] B) user authentication center's webservice server After receiving the full-site logout request, the program calls the UCenter: loginUCenter () method to process the login request: /*** log out of the whole site processing *** @ param string-unique session id of the whole site. use ticket * @ return boolean */static public function logoutUCenter ($ sessId) {self :: _ init (); session_id (trim ($ sessId); session_start (); $ _ SESSION = array (); return empty ($ _ SESSION )? True: false;}?>

4. code deployment:

1. user authentication center settings

A) the webservice interface file provided by the user verification center to the substation, that is, UserSvc. php, is deployed in hostname/webapps/port/UserSvc. php. To view the wsdl content, visit # UserSvc. php? Wsdl

B) in the user Center, the user's SPOF service file is UCenterSSO. class. php, and the file path is hostname/webapps/include/UCenterSSO. class. php. This file is the server class for user single-point login processing and is called by hostname/webapps/port/UserSvc. php. It is used to obtain user login information, whether to perform single-point login status information, single-point logout processing, and so on.

C) the user verification center uses W3C standards and uses cookies to record and delete the script file hostname/webapps/port/cookie_mgr.php, which is the unique random id of users in the whole site.

2. configure sub-sites

A) deploy UClientSSO. class. php in the user Center service client directory. After deployment, modify the UClientSSO: setSite ('1') of the last line. the parameter value is the id assigned to each site by the user verification center.

B) in the api directory under the deployed User Center service client package, transfer the logout_sso.php script here and write the processing script for logging out of this site.

C) the code section for verifying the user login status at the sub-site is added to the single-point login verification process in the user Center.

That is, you must first verify the user's login status through this site. if the user does not pass the verification, go to the user Center for verification. The verification operation calls the UClientSSO: checkUserLogin (); interface. for the interface meaning, see the code comment.

D) in the logout script of the substation, use UClientSSO: getSynlogoutScript (); to obtain the output of the script string.

5. extended functions:

1. record and track all online users

Because all users' logins must go through the user verification center, and all users' ticket are generated in the verification center, you can create a ing table between the user and the ticket (session id) in the memory table. Obtain the records of all online users.

If it is necessary to track the user status in the future to implement other functions, you only need to track the ing table. Other functions include obtaining the online user list, determining the online user status, and obtaining the number of online users.

2. special statistical processing

Because the logon and logout of the entire system must go through the user verification center, special user statistics can be processed. Such as the number of logon times, logon time, logon status failure time, and the trend of online users in each time period.

6. other matters:

1. question about the effective time of the login status on this site:

The whole site requires that the user login status will expire when the browser is closed. The sub-stations are required to handle the session or cookie as follows:

A) the site in which the Session method records the user's login status

Add the code at the beginning of the site public script


B) websites that record user login status in cookie mode

When setting the cookie in the user login status, set the cookie validity period to null.

The above is the content of the PHP version single-point login implementation solution instance. For more information, please follow the PHP Chinese network (www.php1.cn )!

Related Article

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.