Home > Mobile >  Simply SSO in one domain
Simply SSO in one domain

Time:06-30

I created simply scriptsso to login to my two applications in the same domain.

In app A I'm generating token with user name then I'm saving this date in storage.

$token = $_COOKIE['PHPSESSID'].'&'.$user;   
file_put_contents('/'.$_COOKIE['PHPSESSID'].'.txt',$token); 

App B check if exists file with session_id = $_COOKIE['PHPSESSID']

if(file_exists('../../appA/'.$_COOKIE['PHPSESSID'].'.txt'))
{
    $token = file_get_contents('../../appA/'.$_COOKIE['PHPSESSID'].'.txt');
    fclose();
  
    //Decode Token
    $token_code = preg_replace('/&.*/s','', $token);
    $token_user = preg_replace('/.*&/s','', $token);
    $whitelist = explode(',', "127.0.0.1","127.0.0.2");

    $result = app_dbQuery("SELECT user FROM 'users` WHERE `user` = $token_email LIMIT 1");
    if((app_dbNumRows($result) == true) && ($token_code == $_COOKIE['PHPSESSID']) && (in_array($_SERVER['REMOTE_ADDR'],$whitelist)))
    {
        header('Set-Cookie: CookieToken='.$_COOKIE["PHPSESSID"].'; Domain=abc.com; Path=/; Secure;');
        
        echo "login";
    }
}

If all ok, script is generating CookieToken which is next checked in header.php App B.

if((!file_exists('../../appA/'.$_COOKIE['PHPSESSID'].'.txt')) && ($_COOKIE['PHPSESSID'] != $_COOKIE['CookieToken']))
{
  session_unset(); 
  if(isset($_COOKIE['CookieToken']))
  {
    header('Location: ../../appA/logout.php');
  }
  
}

When click logout.php, file token is remove and when someone doesn't click logout.php or browser get close then system remove all file token in storage older than 24 hours. What do you think about my idea about simply SSO, login two apps with the same domain?

CodePudding user response:

You don't have to change the session ID. In a simple way, you can do something like this for app A:

<?php
session_start();
//do what you need
//...
if(!isset($_SESSION['sso'])
   $_SESSION['sso'] = [];
$_SESSION['sso']['user'] = $user;
$_SESSION['sso']['other_info'] = $other_info;
//...

The cookie on the webbrowser will only have the session ID as value. No other information is set in it. The $_SESSION datas are in the session manager of your server.

In app B, you have just to take the value of $_SESSION :

<?php
session_start();
//...
if(isset($_SESSION['sso'])){
   $user = isset($_SESSION['sso']['user']) ? $_SESSION['sso']['user'] : null;
   //do the control with your database
}
//...

But, for use session like that, becareful about the session manager of your 2 app :

  • if it's PHP or file : the 2 app have to be on the same server and share the same session manager
  • if you use 2 servers, one for each app, or use clusters : the session manager must be external like memcache or redis or database.
  • Related