Example _php example of single sign-on implementation scheme in PHP version

Source: Internet
Author: User
Tags error status code php language session id php script stub trim unique id ticket

Summary:

This paper mainly introduces the analysis and design of a universal single sign-on system by using Webservice,session,cookie technology. The specific implementation of the language for PHP. Single sign-on, English name Sign on, referred to as SSO, is the current enterprise, network services, the user integrated processing an important part. The definition of SSO is that in multiple application systems, users can access all trusted applications with only one login.

Motivation:

Friends who have used Ucenter's full station login should all know that this is a typical observer-mode solution. User Center as a subject, the registration and deletion of its observer belong to the background of Ucenter. And each child application site corresponds to a observer. Every time the User Center login action, the JS script will be invoked to callback the standard sub-station login interface (api/uc.php).

The disadvantages of this approach, I think, are mainly two points: 1. Sub-site too much, the callback interface increased, this in the distribution of the number of sub-station restrictions, how to control to make the login efficiency is not too low, not easy to grasp; 2. When there is a problem with a child station callback interface, the default logon process is jammed (you can limit the execution time of the logon program, but the corresponding callback interface for the child station following the problem child station is not available).

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

I. Landing principle Notes

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 for login, according to the user provided the login information, authentication system for authentication, if through effectiveness, should return to the user a certified credential--ticket; When users visit other applications, they will take this ticket, as their credentials, the application system to accept the request will be sent to the ticket certification system to check the legality of the ticket. With effectiveness, users can access application 2 and application System 3 without having to log in again.

As you can see, to achieve SSO, you need the following major features:

(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 the users who have already logged in, and can automatically determine whether the current user has logged in, thus completing the single sign-on function

Based on the above basic principles, I used the PHP language design a set of single sign-on system program, has been put into the official build server run. This system program, will ticket information to the whole system only session ID as the medium, thus obtains the current on-line user's entire station information (login status information and other need to deal with the user whole station information).

Two. Process Description:

Landing process:

1. First visit to a certain station:

A user input username + password, send login request to user authentication Center

b The current login site, through the WebService request, user Authentication Center authentication user name, password legality. If validation passes, generates ticket that identifies the user of the current session and logs the site identifier of the current login to the user center, and finally

C returns the obtained user data and ticket to the child station. If validation does not pass, the appropriate error status code is returned.

D according to the previous step of the WebService request returned results, the current sub-station to the user login processing: If the status code indicates success, then the current site through this station cookie save ticket, and this station record the user's login status. If the status code indicates a failure, the user is given a corresponding login failure prompt.

2. In the state of landing, the user is transferred to another child:

A) through the site cookie or session to verify the user's login status: such as validation 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, then carries on the local login processing to the returned user information. Otherwise, the user is not logged in.

Log out process

A the current logout of the user site to clear the login status and local saved users full station unique random ID

(b) Through the WebService interface, clears the total station unique random ID of the total station record. The WebService interface will return, log out other logged in child station JavaScript code, this station output this code.

c) JS code access to the corresponding station of the standard logout 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 to download.

1. Landing process:

The Uclientsso::loginsso () method must be invoked by the user starting with the browser opening and the first landing of the subweb. This method returns the full station unique random ID used to identify the user. The random ID has been saved through this site cookie in Uclientsso::loginsso (), that is, the subweb retains the stub of the user's login ID.

A) The Uclientsso::loginsso () method is as follows:

 <?php/** * User Authentication Center Login user Processing * @param string $username-user name * @param string $password-user's original password * @param bool EAN $remember-whether to permanently remember the login account * @param boolean $ALREADYENC-whether the incoming password has been simpleencpass encrypted * * @return Array-integer $                                                 return[' status ' is greater than 0: Returns the user ID, indicating that the user login succeeded *-1: The user does not exist, or is deleted *-2: Wrong password *                     -11: Authenticode Error * string $return [' username ']: username * string $return [' Password ']: password * string $return [' email ']: email/static public
function Loginsso ($username, $password, $remember =false, $alreadyEnc =false) {self::_init (); Self::_removelocalsid ();

$ret = Array (); 1. Handling parameters for incoming WebService interfaces//$_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. Call the WebService interface for landing processing//$aRet = Self::_callsoap (' Loginucenter ', $_params); if (Intval ($aRet [' Resultflag ']) > 0 && $aRet [' sessid ']) {//successful login//set local session ID SELF::_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 service program of the user authentication center, after receiving the login authentication request, invokes 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 ($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 for the entire station, as the ticket Total station////co-centric station callback login interface (set User Center unified 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)); Domain-wide cookie settings for a cooperative site 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 (');

Self::registerloggedsite ($siteFlag, $ret [' sessid '])//Remember the landing///
unset ($ret [' userinfo '] [' salt ']);
return $ret;

 }?>

2. After the successful landing of the site, the localization of the user login processing, and then verify that the user is logged on only local verification. (Local access to login user status information, please set to close browser to exit)

3. When checking the user login status, please call local authentication processing, if 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 '] is greater than 0: Returns the user ID, indicating the user login succeeded *                        0: The user does not log in the whole station *-1: The user does not exist, or is deleted *-2: Wrong password * -3: No single sign-on processing *-11: Authenticode Error * str ing $return [' username ']: username * string $return [' Password ']: Password * string $re
 turn[' 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]) {////According to the user name and password in the cookie to determine whether the user has logged in.
 
 $_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 logged in, through the reserved Sesson ID stub to the User Center verification//$_params = Array (' sessid ' => $_sessid, ' Siteflag ' => 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's WebService service program, after receiving the inspection request, calls the Ucenter::getonlineuser () method to process the login request: [php]/** * Obtains the current logged in user information according to the SID * * @param string $sessId-Whole station unique session ID, used for ticket * @return Array * */** * Based on SID, get current logged in User information * * @param string $se SsId-Whole station 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 to have landed war unset ($ret [' userinfo '] [' salt ']);
 else {$ret [' resultflag '] = "0";
 return ($ret);

 }?>

4. When a single point is logged out, the Uclientsso::logoutsso () method is invoked. After the successful call, please call the Uclientsso::getsynloginscript () method to obtain the standard script for the Web page output, if you need to log out of the other landing station immediately.

A) The Uclientsso::logoutsso () method is as follows:

<?php/** * All station single point log out *-Cancellation of the user's total station unique ID via WebService request * @return Integer 1: Success *-11: Validation code Error/Public s
    tatic function Logoutsso () {self::_init ();
    $_sessid = Self::_getlocalsid ();
        This site does not login, do not let the synchronization log out of other stations//if (empty ($_sessid)) {self::_initsess (true);
    return false; } $_params = Array (' sessid ' => $_sessid, ' Siteflag ' => self:: $site, ' checksum ' => m
    D5 ($_sessid. Self:: $site. Self::$_mccomunicationkey));
    $aRet = Self::_callsoap (' Logoutucenter ', $_params);        if (Intval ($aRet [' Resultflag ']) > 0) {//successfully log out self::_removelocalsid ();
        Remove sid stub Self::$_synlogoutscript = UrlDecode ($aRet [' script ']) of this site record;
    $ret = 1;
    else {$ret = $aRet [' Resultflag '];
Return Intval ($ret); [/php] b) The WebService service program of the user authentication center, after receiving the full station logout request, calls the Ucenter::loginucenter () method to process the login request:/** * Log out Total Station processing * * @param stri NG-All 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 substation, that is, usersvc.php deployed in hostname/webapps/port/usersvc.php. To view the WSDL content, please visit the HTTPS://HOSTNAME/PORT/USERSVC.PHP?WSDL

b The User Center user's single point service class file is UCenterSSO.class.php and the file path is hostname/webapps/include/ucentersso.class.php. The file is the user's single sign-on processing service-side class, which is called by hostname/webapps/port/usersvc.php. For access to the user's login information, whether a single point of state information, single point logout processing.

c The user authentication Center through the universal standard, using the cookie method record, deletes the entire station unified user unique random ID The script file for hostname/webapps/port/cookie_mgr.php.

2. Sub-Site Settings

(a) Each subweb, deploy the UClientSSO.class.php in the User Center service client directory. After deployment, modify the last line of Uclientsso::setsite (' 1 '); The parameter values are the identity IDs 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 a processing script to log out of the site.

C in the subweb to verify the user login status of the Code section, an additional increase to the user center of the single sign-on authentication processing.

That is, in the first through the site to verify the user's login status, if not validated, then to the User Center verification. Validation operation to invoke Uclientsso::checkuserlogin (); interface, check the code comments.

(d) In the Log out processing script of the substation, through the Uclientsso::getsynlogoutscript (), the script string output can be obtained.

Five. Extended function:

1. Record Tracking all online users

Because all users ' logins go through the user Authentication center, all users ' ticket are generated at the validation center, and the user and the ticket (session ID) can be set up in a mapping table in the memory table. Get a list of all online users ' records.

Later, if it is necessary to track user status to implement other functions, just follow this mapping table. Other features can be: Get online user list, Judge user online status, get online user number, etc.

2. Special statistical treatment

Because the entire system login log out to the user authentication center, so can be targeted at the user's special statistics for processing. such as user's daily login times, landing time, landing status failure time, the number of online users in each period trend.

Six. Other matters:

1. The station landing state valid time question:

The full station requires user login status to expire when the browser is closed. The sessions or cookies are required to be processed by each branch in the following manner:

A the site that records the user's login status in session mode

Please add the code at the beginning of the site common script

 <?php
 session_write_close ();
 Ini_set (' Session.auto_start ', 0);          Close session automatically start
 ini_set (' Session.cookie_lifetime ', 0);      Sets the session to fail
 ini_set (' Session.gc_maxlifetime ', 3600) when the browser is closed, and//session the duration of the browser not closed   
 ?>

b cookies to record the user login status of the site

Set the cookie valid time to NULL when setting a cookie for user login status.

Original link: http://www.cnblogs.com/linzhenjie/archive/2012/08/24/2653585.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.