SSO Single Sign-on PHP simple version

Source: Internet
Author: User
Tags setcookie

There is a new project in front that requires user resources to be shared. Since have not done such things before, go home immediately after the website Baidu "single Sign In". Post a lot, after screening, here are a few think more nutritious.

Http://blog.csdn.net/ghsau/article/details/20545513,http://blog.sina.com.cn/s/blog_5f66526e0102vf43.html

If you want to solve the problem of synchronous sign-on (Single sign-on) between two websites, first look at the login problem of a website.

Many people know a website login problem, PHP is not put through $_session[' user ']=array (' username ' = ' user1 '), then, look at the code of PHP, do those operations. Under Windows Wamp Environment with PHP configuration file php.ini Look at the session of the relevant knowledge?

In PHP, the session processing scheme is provided by default and can be seen in the php.ini configuration file with such two lines,

Session.save_handler=file

Session.save_path = "E:/wamp/tmp", as

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/348680/201701/348680-20170110135108041-47367263. PNG "style=" margin:0px;padding:0px;border:0px; "/>

These two sentences tell us, the session in PHP processing is the file files, the place is e:/wamp/tmp, look at my file directory down

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/348680/201701/348680-20170110142416588-572642628. PNG "style=" margin:0px;padding:0px;border:0px; "/>

Well, this is the legendary session, to see, to order a bird. You can open it with Notepad and see some characters, which is the string after the serialization of the PHP object array. is to serialize the session object, write to the file, to achieve the session persistence. If the default configuration is used, the session files of multiple websites are present in one place. In other words, if there are two sites on the same server, the session files of site A and site B are stored in one place, and the session file has its own unique identifier, SessionID. SessionID is generated, SessionID is unique, and this sessionid corresponds to the persistent file name of the session. PHP through the SessionID to get the session file, deserialization, you can reach the session read function. In this case, will not think, if the two sessionid the same words, users in the site a login, the user to visit the site B, if SessionID the same, is already the status of the login.

Resolution: Two websites SessionID the same idea

PHP provides session_id () This function can be obtained to SessionID, can be set SessionID. In native PHP, can be implemented through SESSION_ID () to modify the SessionID, in some of the framework is difficult to implement, need to delve into the framework code, why difficult to realize, here to understand session_id () and Session_Start () some association, You need to set SessionID before you go to Session_Start (). So in the framework, the Session_Start () is automatically enabled, so after booting, the SessionID is not modified.

SessionID the same way, is that the browser modification sessionid,sessionid is stored in the cookie, in the configuration file, you can see session.name = PHPSESSID, Then this PHPSESSID is the name of SessionID in the cookie. Such as

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/348680/201701/348680-20170110161613947-1676322779. PNG "style=" margin:0px;padding:0px;border:0px; "/>

Each interaction between the browser and the server, this cookie value will be passed to the server, so if our front desk to modify this value, you can let two sites common a SessionID value.

Specific implementation: In the site B all the page user load, to request the site a interface, to see if the user has logged in, if there is, put back SessionID to site B, site B after receiving SessionID, modify the browser cookie PHPSESSID value. So that the user of site B again to operate, will find themselves sessionid corresponding session file with Site A is the same, so as to achieve synchronization login.

What the site B code needs to do is that every visit to the page needs to ask for a site's data to determine if the user is logged on a site.

  

650) this.width= 650, "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

<if condition= "!session ('? member ')" ><!--not logged in--><script type= "Text/javascript" >     function setcookie (Name,value)     {         document.cookie = name +  "=" + escape  (value) + ";p ath=/"; &NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;//JSONP Login Function     function jsonp_do ( Data)     {      //log (");    }     <{~ $t =time ()}>    $ (document). Ready (function () {       $.ajax ({        type: ' Get ',         url: "<{:c (' Sso_site ')}>?_ts=<{$t}>&_token=<{:md5 ($t. C (' SecretKey ')) }> ",         datatype: ' Jsonp ',         crossdomain: true,        jsonp:  "Callback",         jsonpcallback: ' Jsonp_do ',         success:function ( Data) {             if (data.error==0) {                 setcookie (' PHPSESSID ', data.sess_id);            }                  },         error: function (Xhr, textstatus, errorthrown) {             //log        }       });     });</script></if>

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Then site A will give the corresponding page to the site B request and return data.

  

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

/**     * [index  User Login]     *  @Author: Wty      *  @DateTime: December 12, 2016 11:22:02     *  @return  [type] [description]     */    public function  index ()     {        //can properly incorporate user IP as encryption factor and browser factor          $token =i (' Get._token ');//encryption String           $timespan =i (' get._ts ');//time stamp          $referer =$_ server[' Http_referer '];//here can limit security URLs          $error =100;         //needs to be configured here          $allow =c (' Allow_ Site ');         if (In_array ($referer, $allow)) {//If it is in the Allow access list           $error =1;            if ($token &&$ TimeSpan) {                $ error=2;                $ Secretkey=c (' Secretkey ');//Key                   $check =md5 ($timespan. $secretKey);                 if ($check = = $token) {                      $error =3;                     if (The session ('? Member ')) {                          $error =0;                          $return =array (' Error ' =>0, ' username ' =>session (' Member.username '), ' sess_id ' =>session_id ());                         echo   ' Jsonp_do ( '. Json_encode ($return). ';                          exit;                     }                 }             }            }         echo   ' Jsonp_do ('. Json_encode (Array (' ERROR ' = $error) ') ';     }

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Now most of the Web site will be used to load-balanced multi-server, if it is multi-server, session storage can be considered memcached or redis, the above said that PHP for the session default storage method is files, if used memcached words, You need to modify the configuration file php.ini

Session.save_handler=memcached

Session.save_path = "tpc://192.168.1.1"

In save_handler=memcached or Memcache here, a little difference, if the configuration is written memcached, the following Save_path will write tcp://192.168.1.1:11211, If it is memcache, Save_path will fill in as 192.168.1.1:11211

Very different.

This simple version of single sign-on is basically done.


SSO Single Sign-on PHP simple version

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.