PHP单点登录SSO简单示例Demo
我本地建了三个测试站点,分别为:
- www.testa.com
- www.testb.com
- www.sso.com
其中,站点sso是用于集中验证的站点。
访问站点testa index.php
<?php
// testa: index.php
$url = urlencode("http://www.testa.com/");
if ($_GET['action'] == 'logout') {
setcookie("islogged");
}
if (isset($_GET['token']) && !empty($_GET['token'])) {
$token = $_GET['token'];
$res = file_get_contents("http://www.sso.com/verify.php?token={$token}");
if ($res == 'yes') {
echo "verify success";
setcookie('islogged', true);
} else {
echo "verify fail";
}
header("Location: index.php");
exit;
}
if ($_COOKIE['islogged'] == true) {
echo "a success";
} else {
echo "fail";
header("Location: http://www.sso.com/index.php?redirect={$url}");
}
程序判断用户是否登录站点testa,如果没有,则跳转到站点sso进行验证。
sso验证登录
首先也是进入index.php
,如果登录过,返回token,并跳转回站点testa,否则跳转到sso登录页面。
<?php
// sso: index.php
$redirect = $_GET['redirect'];
if ($_COOKIE['islogged'] == true) {
session_start();
if (isset($_COOKIE['token']) && !empty($_COOKIE['token'])) {
$token = $_COOKIE['token'];
} else {
$token = md5(time());
setcookie('token', $token);
}
echo $token;
header("Location: {$redirect}index.php?token={$token}");
} else {
header("Location: login.php?redirect={$redirect}");
}
<?php
// sso: login.php
$redirect = $_GET['redirect'];
if ($_POST['action'] == 'login') {
$account = $_POST['account'];
$passwd = $_POST['passwd'];
if ($account == 'test' && $passwd == '123456') {
setcookie('islogged', true);
header("Location: index.php?redirect={$redirect}");
}
}
?>
<form action="" method="post">
<input type="hidden" name="action" value="login" />
<p>account: <input type="text" name="account" /></p>
<p>password: <input type="password" name="passwd" /></p>
<input type="submit" value="Submit" />
</form>
token验证
在站点sso成功登录之后,会跳转回testa,并且url中带了token值。然后testa会请求sso验证token值的真实性,如果通过验证,则testa登录成功。
<?php
$token = $_GET['token'];
session_start();
// 由于只是简单示例,这里没有存储token到数据库,仅做展示用
if ($token == 'e4847c591b7a2b60e3d1b40ab9eeeb22') {
echo "yes";
} else {
echo "no";
}
testb 站点登录
站点testb和testa的代码一致,唯一区别的地方是redirect地址是www.testb.com。由于是同一个浏览器,sso站点会直接返回token给testb,验证通过后,用户也就同时登录了testb。
备注:如果是退出登录,一般只能单独退出testa或testb,sso站点需要设置过期时间。或者退出某一个站点时,连带注销sso的登录。