Home >Backend Development >PHP Tutorial >Example of PHP single sign-on implementation solution
Abstract:
This article mainly introduces the analysis and design of a universal single sign-on system using webservice, session, and cookie technologies. The specific implementation language is PHP. Single sign-on, also known as Single Sign On in English, or SSO for short, is an important part of the comprehensive processing of users in current enterprises and network businesses. The definition of SSO is that in multiple application systems, users only need to log in once to access all mutually trusted application systems.
Motivation:
Friends who have used ucenter’s full-site login method should know that this is a typical observer pattern solution. The user center is a subject, and the registration and deletion of its observers are unified in the backend of ucenter. Each sub-application site corresponds to an observer. Every login action in the user center will trigger a js script to call back the w3c standard subsite login interface (api/uc.php).
The shortcomings of this method, I think, are mainly two points: 1. When there are too many sub-sites, the callback interface will increase accordingly. This is limited by the number of distributed sub-sites. How to control it so that the login efficiency will not be affected? Too low and difficult to grasp; 2. When a problem occurs with the callback interface of a certain substation, the default login process will be stuck (the execution time of the login program can be limited, but if there is a corresponding problem, the callback interface of the substation behind the substation will be called No more.
Based on the above issues, during the actual development process, I designed another single sign-on system
1. Login principle explanation
Technical implementation mechanism of single sign-on: When the user accesses application system 1 for the first time, because he has not logged in yet, he will be directed to the authentication system to log in; based on the login information provided by the user, the authentication system performs identity verification , if it passes the validation, an authentication credential - ticket should be returned to the user; when the user accesses other applications, he will bring this ticket as his own authentication credential. After the application system receives the request, it will send the ticket Go to the authentication system for verification and check the validity of the ticket. If it passes the verification, the user can access application system 2 and application system 3 without logging in again.
It can be seen that to implement SSO, The following main functions are required:
a) All application systems share an identity authentication system;
b) All application systems can identify and extract ticket information;
c) Application The system can identify users who have logged in, and can automatically determine whether the current user has logged in, thereby completing the single sign-on function
Based on the above basic principles, I designed a set of single sign-on system programs in PHP language , has now been put into official production server operation. This system program uses the ticket information with the unique session id of the entire system as a medium to obtain the current online user's entire site information (login status information and other user-wide site information that needs to be processed).
2. Process description:
Login process:
1. Log in to a site for the first time:
a) The user enters the username + password and sends a login request to the user verification center
b) When currently logging into the site, through a webservice request, the user verification center verifies the legitimacy of the username and password. If the verification is passed, a ticket is generated to identify the user of the current session, and the site identifier of the currently logged in sub-site is recorded in the user center. Finally,
c) return the obtained user data and ticket to the sub-site. stand. If the verification fails, the corresponding error status code is returned.
d) According to the result returned by the webservice request in the previous step, the current sub-site logs in the user: if the status code indicates success, the current site saves the ticket through the cookie of this site, and the site records the user's Login status. If the status code indicates failure, the user will be given a corresponding login failure prompt.
2. In the logged-in state, the user goes to another page:
a) Verify the user's login status through the site's cookie or session: If the verification is passed, enter the normal site processing program; Otherwise, the user center verifies the user's login status (sends a ticket to the user verification center). If the verification is passed, local login processing is performed on the returned user information. Otherwise, it indicates that the user is not logged in.
Logout process
a) The current logout site clears the user’s login status of the site and the locally saved user’s unique random ID
b) Through the webservice interface, clear the unique random ID recorded in the entire site. The webservice interface will return, log out the javascript code of other logged-in sub-sites, and this site will output this code.
c) js code accesses the W3C standard logout script of the corresponding site
3. Code description:
The relevant code involved in this article has been Package and upload. If you are interested, you can click to download at the download link at the end of this article.
1. Login process:
Starting from opening the browser, the first subsite logged in must call the UClientSSO::loginSSO() method. This method returns a random ID that is unique to the entire site and is used to identify the user. This random ID has been saved through the cookie of this website in UClientSSO::loginSSO(), that is, the sub-site retains the stub of the user's login ID on this website.
a) UClientSSO::loginSSO() method is as follows:
<?php /** * 用户验证中心 登陆用户处理 * * @param string $username - 用户名 * @param string $password - 用户原始密码 * @param boolean $remember - 是否永久记住登陆账号 * @param boolean $alreadyEnc - 传入的密码是否已经经过simpleEncPass加密过 * * @return array - integer $return['status'] 大于 0:返回用户 ID,表示用户登录成功 * -1:用户不存在,或者被删除 * -2:密码错 * -11:验证码错误 * string $return['username'] : 用户名 * string $return['password'] : 密码 * string $return['email'] : Email */ static public function loginSSO($username, $password, $remember=false, $alreadyEnc=false) { self::_init(); self::_removeLocalSid(); $ret = array(); // //1. 处理传入webservice接口的参数 // $_params = array( 'username' => $username, 'password' => $alreadyEnc ? trim($password) : 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.调用webservice接口,进行登陆处理 // $aRet = self::_callSoap('loginUCenter', $_params); if (intval($aRet['resultFlag']) > 0 && $aRet['sessID']) { //成功登陆 //设置本地session id self::_setLocalSid($aRet['sessID']); //设置用户中心的统一session id脚本路径 self::$_synloginScript = urldecode($aRet['script']); $ret = $aRet['userinfo']; } else { $ret['status'] = $aRet['resultFlag']; } return $ret; }//end of function //b) 用户验证中心的webservice服务程序,接收到登陆验证请求后,调用UCenter::loginUCenter()方法来处理登陆请求。 /** * 用户验证中心 登陆用户处理 * * @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 ($res_login < 1) { //登陆失败 } else { //登陆成功 $_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(); //生成全站的唯一session id,作为ticket全站通行 // //合作中心站回调登陆接口(设置用户中心的统一session id) // self::_createCoSitesInfo(); $uinfo = array(); $_timestamp = time(); $_rawCode = array( 'action' => 'setSid', 'sid' => $ret['sessID'], 'time' => $_timestamp, ); if ($remember) { $uinfo = array( 'remember' => 1, 'username' => $username, 'password' => $password ); } $ret['script'] = ''; $_rawStr = http_build_query(array_merge($_rawCode, $uinfo)); // // 合作站点的全域cookie设置脚本地址 // foreach ((array)self::$_coSitesInfo as $_siteInfo) { $_code = self::authcode($_rawStr, 'ENCODE', $_siteInfo['key']); $_src = $_siteInfo['url'] . '?code=' . $_code . '&time=' . $_timestamp; $ret['script'] .= urlencode(''); } // // 记住已登陆战 // self::registerLoggedSite($siteFlag, $ret['sessID']); unset($ret['userinfo']['salt']); } return $ret; } ?>
2. After successful login to this site, localized user login processing is performed, and subsequent verification of whether the user is logged in is only performed locally. (To access information about logged-in user status locally, please set it to exit after closing the browser)
3. When detecting user login status, please call the local verification process first. If the local verification fails, call again The UClientSSO::checkUserLogin() method goes to the user center to detect the user's login status.
a) UClientSSO::checkUserLogin() method is as follows:
<?php /** * 用户单点登陆验证函数 * * @return array - integer $return['status'] 大于 0:返回用户 ID,表示用户登录成功 * 0:用户没有在全站登陆 * -1:用户不存在,或者被删除 * -2:密码错 * -3:未进行过单点登陆处理 * -11:验证码错误 * string $return['username'] : 用户名 * string $return['password'] : 密码 * string $return['email'] : Email */ public static function checkUserLogin(){ self::_init(); $ret = array(); $_sessId = self::_getLocalSid(); if (empty($_sessId)) { //永久记住账号处理 if(isset($_COOKIE[_UC_USER_COOKIE_NAME]) && !empty($_COOKIE[_UC_USER_COOKIE_NAME])) { // // 根据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 { // //本站原先已经登陆过,通过保留的sesson id存根去用户中心验证 // $_params = array( 'sessId' => $_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) 用户验证中心的webservice服务程序,接收到检验登陆的请求后,调用UCenter::getOnlineUser()方法来处理登陆请求: [php]/** * 根据sid,获取当前登陆的用户信息 * * @param string $sessId - 全站唯一session id,用做ticket * @return array */ /** * 根据sid,获取当前登陆的用户信息 * * @param string $sessId - 全站唯一session id,用做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); //记住已登陆战 unset($ret['userinfo']['salt']); } else { $ret['resultFlag'] = "0"; } return ($ret); } ?>
4. When single-point logout, call UClientSSO::logoutSSO( )method. After the call is successful, if you want other logged-in sites to log out immediately, please call the UClientSSO::getSynloginScript() method to obtain the W3C standard script and output it on the page.
a) UClientSSO::logoutSSO() method is as follows:
<?php /** * 全站单点登出 * - 通过webservice请求注销掉用户的全站唯一标识 * * @return integer 1: 成功 * -11:验证码错误 */ public static function logoutSSO(){ self::_init(); $_sessId = self::_getLocalSid(); // //本站没有登陆的话,不让同步登出其他站 // 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) { //成功登出 self::_removeLocalSid(); //移除本站记录的sid存根 self::$_synlogoutScript = urldecode($aRet['script']); $ret = 1; } else { $ret = $aRet['resultFlag']; } return intval($ret); } [/php] b) 用户验证中心的webservice服务程序,接收到全站登出请求后,调用UCenter::loginUCenter()方法来处理登陆请求: /** * 登出全站处理 * * @param string - 全站唯一session id,用做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 service interface file provided by the User Authentication Center to the sub-site, namely UserSvc.php, is deployed in hostname/webapps/port/ UserSvc.php. To view wsdl content, please visit //m.sbmmt.com/ UserSvc.php?wsdl
b) The user center user single-point service class file is UCenterSSO.class.php, and the file path is in hostname/ webapps/include/UCenterSSO.class.php. This file is the server class for user single sign-in processing and is called by hostname/webapps/port/UserSvc.php. Used to obtain the user's login information, status information about whether to log in single-point, single-logout processing, etc.
c) The User Authentication Center passes W3C standards and uses cookies to record and delete the unique random ID of users across the site. The script file is hostname/webapps/port/cookie_mgr.php.
2 Sub -site settings
A) For sub -sites, please, uclientso.class.php is deployed in the service client directory of the user center. After deployment, please modify the last line of UClientSSO::setSite('1'); The parameter value is the identification id uniformly assigned to each site by the user verification center.
b) Serve the client in the deployed user center In the api directory under the package, please transfer the logout_sso.php script here and write a processing script for logging out of this site.
c) In the code section for verifying user login status on the subsite, additional single sign-on verification processing in the user center is added.
That is, first verify the user's login status through this site. If the verification fails, go to the user center for verification. The verification operation requires calling the UClientSSO::checkUserLogin(); interface. Please see the code comments for the meaning of the interface.
d) In the logout processing script of the branch station, use UClientSSO::getSynlogoutScript(); to obtain the script string output.
5. Extended functions:
1. Record and track all online users
Because all user logins must go through the user verification center, all users The tickets are generated in the verification center, and a mapping table can be established between the user and the ticket (session id) in the memory table. Get a record list of all online users.
If it is necessary to track the user status in the future to implement other functions, just track this mapping table. Other functions can be: obtaining a list of online users, determining the user's online status, obtaining the number of online users, etc.
2. Special statistical processing
Because the entire system login and logout must go through the user verification center, special statistics of users can be processed. Such as the number of user logins per day, login time, login status expiration time, the trend of the number of online users in each period, etc.
6. Other matters:
1.
#1. The state is lost when the browser is closed. Each branch station is required to handle sessions or cookies as follows:
a) Sites that record user login status in Session mode
<?php session_write_close(); ini_set('session.auto_start', 0); //关闭session自动启动 ini_set('session.cookie_lifetime', 0); //设置session在浏览器关闭时失效 ini_set('session.gc_maxlifetime', 3600); //session在浏览器未关闭时的持续存活时间 ?>