Home  >  Article  >  Backend Development  >  PHP sso single sign-on implementation code_PHP tutorial

PHP sso single sign-on implementation code_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:10:20941browse

Several points are discussed in detail below. 1. Click Login to jump to the SSO login page and bring the callback address of the current application. 2. After successful login, generate a COOKIE and pass the COOKIE to the callback address. 3. The callback address receives the SSO COOKIE and sets it under the current domain and then jumps back to Apply 1 to complete the login 4. Then embed an iframe in the place where the application needs to be logged in to detect the login status in real time

The code is as follows
 代码如下 复制代码

 


//index.php 应用程序页面
header('Content-Type:text/html; charset=utf-8');
$sso_address = 'http://2spaoku.com/sso/login.php'; //你SSO所在的域名
$callback_address = 'http://'.$_SERVER['HTTP_HOST']
.str_replace('index.php','',$_SERVER['SCRIPT_NAME'])
.'callback.php'; //callback地址用于回调设置cookie

if(isset($_COOKIE['sign'])){
exit("欢迎您{$_COOKIE['sign']} 退出");
}else{
    echo '您还未登录 点此登录';
}
?>

//login.php SSO登录页面
header('Content-Type:text/html; charset=utf-8');
if(isset($_GET['logout'])){
setcookie('sign','',-300);
unset($_GET['logout']);
header('location:index.php');
}

if(isset($_POST['username']) && isset($_POST['password'])){
setcookie('sign',$_POST['username'],0,'');
header("location:".$_POST['callback']."?sign={$_POST['username']}");
}

if(empty($_COOKIE['sign'])){
?>


用户名:


密  码:





}else{
$query = http_build_query($_COOKIE);
echo "系统检测到您已登录 {$_COOKIE['sign']} 授权 退出";
}
?>

//callback.php 回调页面用来设置跨域COOKIE
header('Content-Type:text/html; charset=utf-8');
if(empty($_GET)){
exit('您还未登录');
}else{
foreach($_GET as $key=>$val){
        setcookie($key,$val,0,'');
    }
    header("location:index.php");
}
?>

//connect.php 用来检测登录状态的页面,内嵌在页面的iframe中
header('Content-Type:text/html; charset=utf-8');
if(isset($_COOKIE['sign'])){
$callback = urldecode($_GET['callback']);unset($_GET['callback']);
$query = http_build_query($_COOKIE);
$callback = $callback."?{$query}";
}else{
exit;
}
?>

 

Copy code

//index .php application page
header('Content-Type:text/html; charset=utf-8');
$sso_address = 'http://2spaoku.com/sso/login.php' ; //The domain name where your SSO is located
$callback_address = 'http://'.$_SERVER['HTTP_HOST']
 '])
            .'callback.php'; //The callback address is used to call back to set the cookie

<🎜>if(isset($_COOKIE['sign'])){
     exit( "Welcome{$_COOKIE['sign']} Exit");
}else{
echo 'You also Not logged inClick here to log in';
}
?>