Summary:
This paper mainly introduces the analysis and design of a universal single sign-on system using Webservice,session,cookie technology. The specific implementation language is PHP. Single-sign-on, the English name of "a" on, referred to as SSO, is the current enterprise, network business users of an important part of the comprehensive processing. The definition of SSO is that in multiple application systems, users only have to log in once to gain access to all applications that trust each other.
Motive:
Friends who have used Ucenter's full-site login method should know that this is a typical observer-mode solution. User Center as subject, its own observer registration and deletion unified in the background of Ucenter. Each sub-application site corresponds to a observer. Every time the User Center login action, the JS script will be triggered to callback the standard subnet login interface (api/uc.php).
The disadvantage of this way, I think is mainly two points: 1. When there are too many sub-sites, the callback interface increases correspondingly, the limit of the amount of the distribution sub-station, how to control to make the login efficiency is not too low, not good grasp; 2. When a sub-station callback interface problems, the default logon process will be stuck (can limit the execution time of the login program, but the corresponding problem occurs in the child station behind the callback interface will not be adjusted.
Based on the above problems, in the actual development process, I designed another set of single sign-on system.
I. Landing principle Description
Single Sign-on technology implementation mechanism: When the user first access to the application System 1, because there is no login, will be directed to the authentication system to log in, according to user-provided login information, authentication system for identity verification, if through validation, should be returned to the user a certified credential--ticket; When the user accesses another application, it will take the ticket, as the credentials of their own authentication, the application system accepts the request will send ticket to the authentication system for validation, check the legality of ticket. If tested, the user can access application System 2 and application 3 without having to log in again.
As you can see, the following key features are required to implement SSO:
A) All application systems share an identity authentication system;
b) All application systems are able to identify and extract ticket information;
c) The application system can identify the user who has logged in, can automatically determine whether the current user has logged in, so as to complete the single sign-on function
Based on the above basic principles, I have designed a single sign-on system with the PHP language program, has been put into the official build server run. The system program, the ticket information to the entire system unique session ID as a medium, so as to obtain the current online users of the entire station information (login status information and other users need to process the entire station information).
two. Process Description:
Login process:
1. First time landing a station:
A) user input user name + password, send login request to user authentication Center
b) The current login site, through the WebService request, the user Authentication Center to verify the user name, password legitimacy. If the validation is passed, the ticket is generated to identify the user of the current session and the site identifier of the current login sub-station is logged to the User center, and finally
c) return the acquired user data and ticket to the child station. If the validation does not pass, the corresponding error status code is returned.
D) According to the results of the previous step of the webservice request returned, the current sub-station to the user login processing: If the status code is successful, then the current site through the website cookie to save ticket, and this site records the user's login status. If the status code indicates a failure, the user will be prompted for the login failure.
2. When logged in, the user goes to another child:
A) through the site cookie or session to verify the user's login status: such as verification through, into the normal site processing program; otherwise, the User Center verifies the login status of the users (sending ticket to the user authentication center), such as authentication, and then local login processing for the returned user information. Otherwise, it indicates that the user is not logged in.
Log Out Process
A) The current log-out station to clear the user's login status and local saved users full station unique random ID
b) through the WebService interface, clear the entire station record of the entire site unique random ID. The WebService interface returns, logs out the JavaScript code of other logged-in sub-stations, and outputs this code on this site.
c) JS code access to the corresponding station of the standard log out script
three. Code Description:
This article refers to the relevant code, has been packaged upload, if interested, you can download the link at the end of this article click Download.
1. Login process:
The user must call the Uclientsso::loginsso () method from the beginning of the browser opening, the first landed subweb. The method returns the full-site unique random ID used to identify the user. The random ID in Uclientsso::loginsso () has been saved through the site cookie, that is, the subweb retains the user has logged on the stub on the site.
A) The Uclientsso::loginsso () method is as follows:
<?php/** * User Authentication Center Login User Processing * * @param string $username-user name * @param string $password-user Original password * @param boolean $rem Ember-whether to permanently remember login account * @param boolean $ALREADYENC-whether the incoming password has been simpleencpass encrypted * * @return array-integer $return [' STA Tus '] greater than 0: return user ID, indicating user login successful *-1: User does not exist, or is deleted *-2: Wrong password * -11: Captcha Error * string $return [' username ']: username * Strin G $return [' Password ']: password * string $return [' email ']: email */static public Function Loginsso ($u Sername, $password, $remember =false, $alreadyEnc =false) {self::_init (); Self::_removelocalsid (); $ret = Array ();////1. Parameters for handling Incoming WebService interface//$_params = Array (' username ' = $username, ' password ' = ' $alreadyEnc trim ($pass Word): Self::simpleencpass (Trim ($password)), ' IP ' = Self::onlineip (), ' siteflag ' = ' self:: $site, ' Remember ' = $remember); $_params[' checksum '] = self::_getchecksum ($_params[' username '). $_params[' Password ']. $_params[' IP '. $_ params[' Siteflag '. $_params[' remember ');////2. Call the WebService interface for login processing//$aRet = Self::_callsoap (' Loginucenter ', $_params); if (Intval ($ aret[' Resultflag ') > 0 && $aRet [' sessid ']) {//Successfully login//Set 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) user Authentication Center of the WebService Service program, after receiving a login authentication request, call 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[' s Tatus ']; $ret[' resultflag ' = $res _login;if ($res _login < 1) {//Login failed} else {//login succeeded $_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 (); Generate a unique session ID of the whole station, as ticket full station////Cooperative Center station callback login interface (set User Center of the unified session ID)//self::_createcositesinfo (); $uinfo = Array (); $_timestamp = time (); $_rawcode = array (' action ' = ' setsid ', ' sid ' = = $ret [' Sessid '], ' Time ' = $_timestamp,); if ($remember) {$uinfo = array (' Remember ' = 1, ' Userna Me ' = $username, ' password ' = $password);} $ret [' script '] = '; $_rawstr = Http_build_query (Array_merge ($_rawcode, $uinfo)),////co-site's global cookie setting script address//foreach (( Array) Self::$_cositesinfo as $_siteinfo) {$_code = Self::authcode ($_rawstr, ' ENCODE ', $_siteinfo[' key '); $_SRC = $_siteinfo[' URL ']. '? code= '. $_code. ' &time= '. $_timestamp; $ret [' script ']. = UrlEncode (");} Remember the landing battle//self::registerloggedsite ($siteFlag, $ret [' sessid ']), unset ($ret [' userinfo '] [' salt ']);} return $ret;}? >
2. After the successful landing of the site, the localization of the user login processing, and then verify whether the user logged in only local authentication. (for local access to log in user status, set to close the browser to exit)
3. When the user login status is detected, please call the local authentication processing, if the local authentication does not pass, then call Uclientsso::checkuserlogin () method to the User center to detect the user's login status.
A) The Uclientsso::checkuserlogin () method is as follows:
<?php/** * User Single Sign-on verification function * * @return array-integer $return [' status '] greater than 0: return user ID, indicating user login successful * 0: The user does not login in the whole station *-1: The user does not exist, or is deleted *-2: Wrong password * -3: No single Sign-on processing *-11: CAPTCHA Error * String $return [ ' Username ': username * string $return [' Password ']: password * string $return [' email '] : Email */public static function Checkuserlogin () {self::_init (); $ret = Array (); $_sessid = Self::_getlocalsid (); if (Empty ($_SESSID)) {//Permanently remember account processing if (Isset ($_cookie[_uc_user_cookie_name]) &&!empty ($_cookie[_uc_user_cookie_name])) {//// Determine if the user has logged in based on the user name and password in the cookie. $_userinfo = Explode (' |g| ', Self::authcode ($_cookie[_uc_user_cookie_name], ' DECODE ', Self::$_authcodekey)); $username = $_userinfo[0]; $password = Isset ($_userinfo[1])? $_USERINFO[1]: "; if (empty ($password)) {$ret [' status'] =-3; } else {return Self::loginsso ($username, $password, True, true);} } else {$ret [' status '] =-3;} } else {/////This site has already landed, through the reserved Sesson ID stub to the User Center authentication//$_params = Array (' sessid ' = = $_sessid, ' si Teflag ' + self:: $site, ' checksum ' = ' MD5 ($_sessid. Self:: $site. Self::$_mccomunicationkey)); $aRet = Self::_callsoap (' Getonlineuser ', $_params); if (Intval ($aRet [' Resultflag ']) > 0) {//successful login $ret = $aRet [' UserInfo '];} else {$ret [' status '] = $aRet [' Resultflag ']; }} return $ret; } b) User authentication center of the WebService Service program, after receiving the inspection login request, call the Ucenter::getonlineuser () method to process the login request: [php]/** * According to the SID, get the current logged user information * * @para M string $sessId-Full station unique session ID, used as ticket * @return Array *//** * Based on SID, get current logged on user information * * @param string $sessId-All stations Unique session ID, 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 the landing battle unset ($ret [' userinfo ' [' salt ']); } else {$ret [' resultflag '] = "0";} return ($ret); }?>
4. When a single point is logged out, call the Uclientsso::logoutsso () method. After the call succeeds, if you need to log out of other logged-in stations immediately, please call the Uclientsso::getsynloginscript () method to get the standard script in the page output.
A) The Uclientsso::logoutsso () method is as follows:
<?php/*** Full Station Single point logout *-Log off the user's full-site unique identity by WebService request * * @return Integer 1: Success *-11: Captcha error */public static fun Ction Logoutsso () {self::_init (); $_sessid = Self::_getlocalsid (); This site does not log on, do not let synchronization log out of other stations//if (empty ($_sessid)) {self::_initsess (true); return false; } $_params = Array (' sessid ' = + $_sessid, ' siteflag ' = = Self:: $site, ' checksum ' = MD5 ($ _sessid. Self:: $site. Self::$_mccomunicationkey)); $aRet = Self::_callsoap (' Logoutucenter ', $_params); if (Intval ($aRet [' Resultflag ']) > 0) {//successfully log out of Self::_removelocalsid (); Remove the SID stub from this site record self::$_synlogoutscript = UrlDecode ($aRet [' script ']); $ret = 1; } else {$ret = $aRet [' Resultflag ']; } return Intval ($ret);} [/php] b) User authentication center of the WebService Service program, after receiving the full station logout request, call the Ucenter::loginucenter () method to process the login request:/*** logout Full Station processing * * @param string- Full station unique session ID, used as ticket* @return boolean*/static public Function loGoutucenter ($sessId) {self::_init (); session_id (Trim ($sessId)); Session_Start (); $_session = Array (); return empty ($_session)? True:false;}? >
four. Code deployment:
1. User Authentication Center Settings
A) The WebService service interface file provided by the user authentication Center to the sub-station, i.e. usersvc.php is deployed in hostname/webapps/port/usersvc.php. To view the WSDL content, visit the HTTP://WWW.PHP.CN/USERSVC.PHP?WSDL
b) User Center user single-point service class file is UCenterSSO.class.php, the file path is in hostname/webapps/include/ucentersso.class.php. The file is a service-side class that is processed by the user single-point login and is called by hostname/webapps/port/usersvc.php. Used to obtain the user's login information, whether a single point of login status information, single-point logout processing.
c) User authentication Center through the standard, using cookies to record, delete the entire site unified user unique random ID script file for hostname/webapps/port/cookie_mgr.php.
2. Child Site Settings
A) Each subweb, UClientSSO.class.php is deployed in the User Center service client directory. After deployment, modify the last line of Uclientsso::setsite (' 1 '); The parameter value is the identity ID that is uniformly assigned to each station by the user authentication Center.
b) Under the API directory under the deployed User Center service client package, transfer the logout_sso.php script here and write the processing script for the logout of the site.
c) in the sub-site to verify the user login status of the Code section, additional to the user center of the single sign-on verification processing.
That is, in the first through the site to verify the user's login status, if not verified, then to the User Center authentication. Verify the operation to invoke Uclientsso::checkuserlogin (); interface, interface meaning please review the code comment.
d) in the logout processing script of the station, pass Uclientsso::getsynlogoutscript (); Get the script string output.
Five. Extended function:
1. Record tracking for all online users
Because all users are logged in through the user authentication center, all users ' ticket are generated in the validation center, and the user and the ticket (session ID) can be created in the memory table to create a mapping table. Get all the online user's record table.
Later, if it is necessary to track the user state to implement other functions, just follow this mapping table. Other functions can be: Get a list of online users, determine the status of users online, access to the number of online users and so on.
2. Special statistical processing
Because the entire system login log out to go through the user Authentication center, so can be processed for the user's special statistics. such as the number of user login per day, login time, login status failure time, the number of online users in various periods of the trend.
Six. Other matters:
1. Valid time of landing status of the site:
The entire station requires that the user login status is disabled when the browser is closed. Each sub-station is required to process the session or cookie as follows:
A) The session to record the user login status of the site
Please add code at the beginning of the site common script
<?php Session_write_close (); Ini_set (' Session.auto_start ', 0); Close Session auto Start Ini_set (' Session.cookie_lifetime ', 0); Set session to expire when the browser is closed Ini_set (' Session.gc_maxlifetime ', 3600); The duration of the session when the browser is not closed ?>
b) Cookies to record the user login status of the site
When setting a cookie for user login status, set the cookie to a valid time of NULL.
The above is the PHP version of the single-point implementation of the example of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!