PHP不到100行代码实现SSO单点登录

1、点击登录跳转到SSO登录页面并带上当前应用的callback地址
2、登录成功后生成COOKIE并将COOKIE传给callback地址
3、callback地址接收SSO的COOKIE并设置在当前域下再跳回到应用1即完成登录
4、再在应用程序需要登录的地方嵌入一个iframe用来实时检测登录状态

 

  1. <?php 
  2. //index.php 应用程序页面 
  3. header('Content-Type:text/html; charset=utf-8'); 
  4. $sso_address = 'http://2spaoku.com/sso/login.php'; //你SSO所在的域名 
  5. $callback_address = 'http://'.$_SERVER['HTTP_HOST'] 
  6.                     .str_replace('index.php','',$_SERVER['SCRIPT_NAME']) 
  7.                     .'callback.php'; //callback地址用于回调设置cookie 
  8. if(isset($_COOKIE['sign'])){ 
  9.     exit("欢迎您{$_COOKIE['sign']} <a href=\"login.php?logout\">退出</a>"); 
  10. }else{ 
  11.     echo '您还未登录 <a href="'.$sso_address.'?callback='.$callback_address.'">点此登录</a>'; 
  12. ?>
  13. <iframe src="<?php echo $sso_address ?>?callback=<?php echo $callback_address ?>" frameborder="0"  width="0" height="0"></iframe>
复制代码
  1. <?php 
  2. //login.php SSO登录页面 
  3. header('Content-Type:text/html; charset=utf-8'); 
  4. if(isset($_GET['logout'])){ 
  5.     setcookie('sign','',-300); 
  6.     unset($_GET['logout']); 
  7.     header('location:index.php'); 
  8. if(isset($_POST['username']) && isset($_POST['password'])){ 
  9.     setcookie('sign',$_POST['username'],0,''); 
  10.     header("location:".$_POST['callback']."?sign={$_POST['username']}"); 
  11. if(empty($_COOKIE['sign'])){ 
  12. ?> 
  13. <form method="post"> 
  14. <p>用户名:<input type="text" name="username" /></p> 
  15. <p>密  码:<input type="password" name="password" /></p> 
  16. <input type="hidden" name="callback" value="<?php echo $_GET['callback']; ?>" /> 
  17. <input type="submit" value="登录" /> 
  18. </form> 
  19. <?php 
  20. }else{ 
  21.     $query = http_build_query($_COOKIE); 
  22.     echo "系统检测到您已登录 {$_COOKIE['sign']} <a href=\"{$_GET['callback']}?{$query}\">授权</a> <a href=\"?logout\">退出</a>"; 
  23. ?>
复制代码
  1. <?php 
  2. //callback.php 回调页面用来设置跨域COOKIE 
  3. header('Content-Type:text/html; charset=utf-8'); 
  4. if(empty($_GET)){ 
  5.     exit('您还未登录'); 
  6. }else{ 
  7.     foreach($_GET as $key=>$val){ 
  8.         setcookie($key,$val,0,''); 
  9.     } 
  10.     header("location:index.php"); 
  11. }
  12. ?>
复制代码
  1. <?php 
  2. //connect.php 用来检测登录状态的页面,内嵌在页面的iframe中 
  3. header('Content-Type:text/html; charset=utf-8'); 
  4. if(isset($_COOKIE['sign'])){ 
  5.     $callback = urldecode($_GET['callback']);unset($_GET['callback']); 
  6.     $query = http_build_query($_COOKIE); 
  7.     $callback = $callback."?{$query}"; 
  8. }else{ 
  9.     exit; 
  10. ?>
  11. <html><script type="text/javascript">top.location.href="<?php echo $callback; ?>";</script></html>
复制代码

演示地址:http://tmkook.com/blog/sso/
源文地址:http://tmkook.com/blog/archives/php-sso
posted @ 2016-07-04 14:30  fleam  阅读(311)  评论(0编辑  收藏  举报