PHP+ajax to achieve cross-domain single sign-on
We have previously introduced the principle of cross-domain single sign-on in "Detailed explanation of the implementation methods of three situations of SSO single sign-on" . Here we will introduce how to implement single sign-on using PHP and Ajax.
In this example we need two sites:
www.onmpw.com
www.onmpw1.com
Of course there is also a verification system
www.SSOsite.com
In order to achieve single sign-on, first, we need to set up two sites to share sessions . As for how to share sessions, you can refer to the article "PHP Cluster Session Sharing" . We will not introduce it in detail here.
Assume that we have set up the two to share a session. Next, we will introduce the specific implementation process.
Part I
Let's describe the process in words:
The browser requests the page that requires authentication from onmpw.
· Request the SSOsite system through ajax to check whether the cookie information of the SSOsite site exists. If not, notify the browser that it needs to log in.
After receiving the information that needs to be logged in , the browser requests the login page of onmpw (of course, some systems use the SSOsite login system uniformly, then the browser needs to request the SSOsite login page again).
Submit the login information to the onmpw system. The onmpw system uses curl technology to send the login information to the SSOsite system for verification.
curl_setopt($ch, CURLOPT_URL, "www.SSOsite.com/?c=Auth&a=authUser");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('username'=>$username,'password'=>$password));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$res = json_decode($data);
After SSOsite authentication succeeds, a token is generated and the user information and the generated token are returned to the onmpw system.
const chars = 'abcdefgABCDEFG012hijklmnHIJKLMN3456opqrstOPQRST789UVWXYZuvwxyz';
static public function str_random(){
//Randomly generate token string
$chars = self::chars;
$token = '';
for($i = 0; $i < 5; $i++){
$str = substr($chars,0,mt_rand(0, strlen($chars)-1));
$token .= $str.$chars[mt_rand(0, strlen($str)-1)];
}
$token = md5($token);
return $token;
}
After receiving the successful authentication information returned by SSOsite, onmpw writes the user information into the browser's cookie. Finally, it responds to the browser with the successful login information .
setcookie('userid',$res->userid,null,'/'); //Set cookies for this site
The browser then sends the obtained token to the SSO site again via ajax .
checkToken:function(args){
$.ajax({
url:Onmpw_SSO.Configure.SSO_Server+'/?c=Auth&a=checkToken',
xhrFields: {withCredentials: Onmpw_SSO.Configure.Cross_Domain},
dataType:'json',
type:'post',
data:{token:args.token,userid:args.userid},
success:function(data){
args.Suc();
},
error:function(err){
console.log(err);
}
})
},
SSOsite得到token以后将token存入浏览器端cookie和session中。
public function checkToken(){
$this->authUrl();
session_start();
if(isset($_POST['token'])){
setcookie('usertoken',$_POST['token'],null);
setcookie('userid',$_POST['userid'],null);
$_SESSION['token'] = $_POST['token'];
echo json_encode(array('auth'=>'SUC'));
}
}
注意在浏览器通过ajax向SSOsite发送请求的情况下需要设置CORS(跨域资源共享)。
private function authUrl(){
$origin = $_SERVER['HTTP_ORIGIN'];
if (in_array($origin, $this->urlArr)) {
header("Access-Control-Allow-Origin:" . $origin);
header("Access-Control-Allow-Credentials: true ");
}else{
echo "error!";
exit;
}
}
设置完成以后,返回浏览器登录成功。
第二部分
下面我们用文字描述该过程
·浏览器请求onmpw的需要验证的页面。
·通过ajax带着cookie信息请求SSOsite系统。SSOsite系统在cookie中提取用户token。然后再次生成一个临时token存入session中,其键名为用户token。最后通知浏览器该用户已经登录成功,并且将临时token一并返回给浏览器。
$tmptoken = \Common::str_random();
$_SESSION[$_SESSION['token']] = $tmptoken;
·浏览器接收到临时token,然后再次通过ajax将临时token发送给SSOsite进行验证。SSOsite验证完成临时token,将session中的临时token销毁。并且得到自己的sessionId返回给浏览器。
public function authToken(){
$this->authUrl();
session_start();
$tmptoken = $_POST['tmptoken'];
if($tmptoken == $_SESSION[$_SESSION['token']]){
unset($_SESSION[$_SESSION['token']]);
echo json_encode(array('auth'=>'SUC','userid'=>$_COOKIE['userid'],'sessionId'=>session_id()));
}else{
echo json_encode(array('auth'=>'FAIL'));
}
}
After the browser receives the sessionId returned by the SSOsite, it sends the sessionId to onmpw. After the onmpw system receives the sessionId from the browser, it uses this sessionId to initialize its own session. The user information previously stored in the browser cookie is stored in the session and the cookie information is destroyed (of course, after the session is opened, we first check whether the user information exists in the session. If not, the user information in the cookie is stored in the session and the cookie is destroyed).
$sessionId = $_POST['sessionId'];
session_id($sessionId);
session_start();
if(!isset($_SESSION['userid'])){
$userid = $_COOKIE['userid'];
setcookie('userid',"",time()-3600,'/');
$_SESSION['userid'] = $userid;
}
· The browser can then know that the user information exists and perform the corresponding operation. After the first part of the steps are completed, the user can also request onmpw1. The steps are the same as those described in the second part.
So far, the process of implementing cross-domain single sign-on through PHP and Ajax has been completed. There is a part of the core code, you can click here to view the complete code. I hope this article will be helpful to you.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
使用 phpMyAdmin 删除 MySQL 数据库中的所有行
Publish Date:2024/03/25 Views:72 Category:MySQL
-
在本指南中,我们将了解使用 phpMyAdmin 从 MySQL 数据库中删除所有行的最佳方法。
循环 PHP MySQLi 获取数组函数
Publish Date:2024/03/25 Views:125 Category:MySQL
-
本教程将指导你了解 php mysqli_fetch_array() 函数,并介绍如何迭代 mysqli 查询。
jQuery 中的 $.Ajax 数据类型
Publish Date:2024/03/24 Views:135 Category:JavaScript
-
本教程演示了在 jQuery 中使用 $.ajax 数据类型。
在 jQuery 中处理 $.ajax 失败
Publish Date:2024/03/24 Views:158 Category:JavaScript
-
在今天的文章中,我们将学习在 jQuery 中处理 AJAX 中的失败请求。
在 jQuery AJAX 中传递请求标头
Publish Date:2024/03/24 Views:142 Category:JavaScript
-
本教程演示了如何在 jQuery AJAX 中使用标头。
jQuery 中的 AJAX POST 请求
Publish Date:2024/03/24 Views:129 Category:JavaScript
-
在今天的文章中,我们将学习 jQuery 中的 AJAX 发布请求。
使用 PHP MySQLi 函数获取最后插入的 ID
Publish Date:2023/05/09 Views:102 Category:MySQL
-
本篇文章简要介绍了 PHP mysqli() 函数并演示了如何使用它从 MySQL 数据库中获取最后插入的 ID。它是一个名为 mysqli 的 MySQL 驱动程序扩展版本,
在 PHP 中使用 MongoDB 作为文件存储
Publish Date:2023/04/20 Views:145 Category:MongoDB
-
在为大文件创建可扩展存储方面,MongoDB 及其 GridFS(使用 MongoDB 查询语言 - MQL 编写)是市场上最好的文件存储解决方案之一。 在本教程中,您将学习如何在 PHP 中使用 MongoDB 作为文件存储。
如何在 PHP 中获取时间差的分钟数
Publish Date:2023/03/29 Views:207 Category:PHP
-
本文介绍了如何在 PHP 中获取时间差的分钟数,包括 date_diff()函数和数学公式。它包括 date_diff()函数和数学公式。