search
HomeBackend DevelopmentPHP TutorialExample 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[&#39;status&#39;] 大于 0:返回用户 ID,表示用户登录成功
 *                        -1:用户不存在,或者被删除
 *                        -2:密码错
 *                                                 -11:验证码错误
 *                     string $return[&#39;username&#39;]   : 用户名
 *                     string $return[&#39;password&#39;]   : 密码
 *                     string $return[&#39;email&#39;]    : Email
 */

static public function loginSSO($username, $password, $remember=false, $alreadyEnc=false) {
self::_init();
self::_removeLocalSid();
$ret = array();

//
//1. 处理传入webservice接口的参数
//
$_params = array(
        &#39;username&#39; => $username,
        &#39;password&#39; => $alreadyEnc ? trim($password) : self::simpleEncPass(trim($password)),
        &#39;ip&#39;    => self::onlineip(),
        &#39;siteFlag&#39; => self::$site,
        &#39;remember&#39; => $remember
);
$_params[&#39;checksum&#39;] = self::_getCheckSum($_params[&#39;username&#39;] . $_params[&#39;password&#39;] .
$_params[&#39;ip&#39;] . $_params[&#39;siteFlag&#39;] . $_params[&#39;remember&#39;]);

//
// 2.调用webservice接口,进行登陆处理
//
$aRet = self::_callSoap(&#39;loginUCenter&#39;, $_params);

if (intval($aRet[&#39;resultFlag&#39;]) > 0 && $aRet[&#39;sessID&#39;]) {
//成功登陆
//设置本地session id
self::_setLocalSid($aRet[&#39;sessID&#39;]);

//设置用户中心的统一session id脚本路径
self::$_synloginScript = urldecode($aRet[&#39;script&#39;]);

$ret = $aRet[&#39;userinfo&#39;];
} else {

$ret[&#39;status&#39;] = $aRet[&#39;resultFlag&#39;];
}

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[&#39;status&#39;];        //
$ret[&#39;resultFlag&#39;] = $res_login;

if ($res_login < 1) {
//登陆失败
} else {

//登陆成功
$_SESSION[self::$_ucSessKey] = $arr_login_res;

$_SESSION[self::$_ucSessKey][&#39;salt&#39;] =
self::_getUserPassSalt($_SESSION[self::$_ucSessKey][&#39;username&#39;], $_SESSION[self::$_ucSessKey][&#39;password&#39;]);

$ret[&#39;userinfo&#39;] = $_SESSION[self::$_ucSessKey];
$ret[&#39;sessID&#39;]  = session_id();    //生成全站的唯一session id,作为ticket全站通行

//
//合作中心站回调登陆接口(设置用户中心的统一session id)
//
self::_createCoSitesInfo();
$uinfo = array();
$_timestamp = time();
$_rawCode = array(
            &#39;action&#39; => &#39;setSid&#39;,
            &#39;sid&#39;  => $ret[&#39;sessID&#39;],
            &#39;time&#39;  => $_timestamp,
);
if ($remember) {
$uinfo = array(
                &#39;remember&#39; => 1,
                &#39;username&#39; => $username,
                &#39;password&#39; => $password
);
}

$ret[&#39;script&#39;] = &#39;&#39;;
$_rawStr = http_build_query(array_merge($_rawCode, $uinfo));

//
// 合作站点的全域cookie设置脚本地址
//
foreach ((array)self::$_coSitesInfo as $_siteInfo) {
$_code = self::authcode($_rawStr, &#39;ENCODE&#39;, $_siteInfo[&#39;key&#39;]);
$_src = $_siteInfo[&#39;url&#39;] . &#39;?code=&#39; . $_code . &#39;&time=&#39; . $_timestamp;
$ret[&#39;script&#39;] .= urlencode(&#39;&#39;);
}

//
// 记住已登陆战
//
self::registerLoggedSite($siteFlag, $ret[&#39;sessID&#39;]);

unset($ret[&#39;userinfo&#39;][&#39;salt&#39;]);
}

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[&#39;status&#39;] 大于 0:返回用户 ID,表示用户登录成功
 *                                                  0:用户没有在全站登陆
 *                        -1:用户不存在,或者被删除
 *                        -2:密码错
 *                        -3:未进行过单点登陆处理
 *                                                 -11:验证码错误
 *                     string $return[&#39;username&#39;]   : 用户名
 *                     string $return[&#39;password&#39;]   : 密码
 *                     string $return[&#39;email&#39;]    : 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(&#39;|g|&#39;, self::authcode($_COOKIE[_UC_USER_COOKIE_NAME], &#39;DECODE&#39;, self::$_authcodeKey));
 
 $username = $_userinfo[0];
 $password = isset($_userinfo[1]) ? $_userinfo[1] : &#39;&#39;;
 if (empty($password)) {
 $ret[&#39;status&#39;] = -3;
 } else {
 return self::loginSSO($username, $password, true, true);
 }
 
 } else {
 $ret[&#39;status&#39;] = -3;
 }
 
 } else {
 //
 //本站原先已经登陆过,通过保留的sesson id存根去用户中心验证
 //
 $_params = array(
             &#39;sessId&#39;  => $_sessId,
             &#39;siteFlag&#39; => self::$site,
             &#39;checksum&#39; => md5($_sessId . self::$site . self::$_mcComunicationKey)
 );
 $aRet = self::_callSoap(&#39;getOnlineUser&#39;, $_params);
 if (intval($aRet[&#39;resultFlag&#39;]) > 0) {
 //成功登陆
 $ret = $aRet[&#39;userinfo&#39;];
 } else {
 $ret[&#39;status&#39;] = $aRet[&#39;resultFlag&#39;];
 }
 }
 
 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[&#39;username&#39;]) && isset($_userinfo[&#39;password&#39;]) &&
 self::_getUserPassSalt($_userinfo[&#39;username&#39;], $_userinfo[&#39;password&#39;])) {
 $ret[&#39;resultFlag&#39;] = "1";
 $ret[&#39;userinfo&#39;] = $_userinfo;
 
 self::registerLoggedSite($siteFlag, $sessId);        //记住已登陆战
 unset($ret[&#39;userinfo&#39;][&#39;salt&#39;]);
 } else {
 $ret[&#39;resultFlag&#39;] = "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(
        &#39;sessId&#39;  => $_sessId,
        &#39;siteFlag&#39; => self::$site,
        &#39;checksum&#39; => md5($_sessId . self::$site . self::$_mcComunicationKey)
    );
    $aRet = self::_callSoap(&#39;logoutUCenter&#39;, $_params);
    if (intval($aRet[&#39;resultFlag&#39;]) > 0) {
        //成功登出
        self::_removeLocalSid();        //移除本站记录的sid存根
        self::$_synlogoutScript = urldecode($aRet[&#39;script&#39;]);
        $ret = 1;
    } else {
        $ret = $aRet[&#39;resultFlag&#39;];
    }
    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 http://www.php.cn/ 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

Please add the following code at the beginning of the site’s public script



<?php
 session_write_close();
 ini_set(&#39;session.auto_start&#39;, 0);          //关闭session自动启动
 ini_set(&#39;session.cookie_lifetime&#39;, 0);      //设置session在浏览器关闭时失效
 ini_set(&#39;session.gc_maxlifetime&#39;, 3600); //session在浏览器未关闭时的持续存活时间   
 ?>



b) Sites that use cookies to record user login status

Please set the cookie validity time to null when setting the cookie for user login status.


######
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools