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
Detailed explanation of the implementation methods of SSO single sign-on in three
Publish Date:2025/03/18 Views:190 Category:NETWORK
-
Single Sign On (SSO) is not unfamiliar to us. For large systems, using SSO can reduce a lot of trouble for users. Take Baidu for example. Baidu has many subsystems - Baidu Experience, Baidu Knows, Baidu Library, etc. If we need to enter a u
Which technology do you choose to implement the web chat room?
Publish Date:2025/03/18 Views:61 Category:NETWORK
-
With the rise of HTML5 Websockets, web chat applications are becoming more and more popular. Recently, I am working on a mobile web application, the core function of which is to implement web chat on the mobile phone. Of course, the functio
Implementing a group chat room using socket.io
Publish Date:2025/03/18 Views:65 Category:NETWORK
-
This article will share with you an example of using socket.io to realize the function of group chat. If you want to use socket.io, you must use nodejs to implement the server, so we need to install socket.io in nodejs Install socket.io How
First contact with CGI
Publish Date:2025/03/18 Views:51 Category:NETWORK
-
Since I am a PHP programmer, I often have to build a PHP operating environment. The popular nginx+php environment is very popular, and the mode it adopts is the FastCGI method, so I spent some time to learn about FastCGI. CGI (Common Gatewa
PHP cluster session sharing
Publish Date:2025/03/18 Views:124 Category:NETWORK
-
The concept of cluster is not complicated. It is actually multiple computers working together for the same goal. In Web applications, multiple servers provide services for a site. The first step to build a PHP cluster is to set up load bala
Ajax cross-domain cookie related settings
Publish Date:2025/03/18 Views:87 Category:NETWORK
-
In web programming, we often encounter cross-domain issues. By default, browsers do not allow cross-domain access. Therefore, there is a concept here: CORS (Cross-Origin Resource Sharing). Before the HTML5 standard came out, CORS was not al
IE's Ajax cross-domain issue
Publish Date:2025/03/16 Views:190 Category:NETWORK
-
Ajax is widely used in web systems, but cross-domain issues are often encountered in web systems. By default, browsers prohibit Ajax cross-domain access. The IE browser has particularly strict restrictions. For browsers such as Firefox, Goo
使用 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 查询。