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
Check if a Post exists in PHP
Publish Date:2025/04/13 Views:170 Category:PHP
-
PHP $_POST is a super global variable that can contain key-value pairs of HTML form data submitted through the post method. We will learn different ways to check $_POST if a and contains some data in this article. These methods will use iss
PHP with Ajax
Publish Date:2025/04/13 Views:139 Category:PHP
-
We will use PHP and ajax by printing a simple sum of two numbers 2 and . Also, print a php array in JSON. 3 object We will also use PHP with ajax by getting the HTML formatted output from the number division in PHP. Printing simple addition
Store Div Id in PHP variable and pass it to JavaScript
Publish Date:2025/04/13 Views:51 Category:PHP
-
This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s
Returns the article tag with ID from the action page
Publish Date:2025/04/13 Views:80 Category:PHP
-
Let's say you're in a login form and you enter the wrong information; in this case, you probably want to go back to the login page. PHP has a built-in function header() to redirect a page to a specific page. But what if the login page is at
Switching PHP versions on Ubuntu
Publish Date:2025/04/13 Views:78 Category:PHP
-
Different tasks may require running multiple versions of PHP. You may need to switch PHP versions by running two sites on the same server or testing older versions of code using outdated methods. We can switch PHP versions on Ubuntu using t
Resizing images in PHP
Publish Date:2025/04/13 Views:155 Category:PHP
-
In this tutorial article, we will discuss about resizing images in PHP. Load the image before resizing Before we can resize an image, we must first load it as an image resource in our script. This is file_get_contents() different from using
PHP upload image
Publish Date:2025/04/13 Views:61 Category:PHP
-
We can upload images in PHP using simple file upload operation, but first, php.ini file upload should be enabled from Files. This tutorial demonstrates how to upload images in PHP. php.ini Enable file upload from file in PHP to upload image
Creating a signature from Hash_hmac() and Sha256 in PHP
Publish Date:2025/04/13 Views:107 Category:PHP
-
PHP has one of the best encryption functions for data security. Hash_hmac() The encrypt function is one of the most famous encryptors. We'll show you how to use hash_hmac and sha256 encryptors to create 安全签名 one that you can store i
Updating PHP 7.x to 7.4 on CentOS
Publish Date:2025/04/13 Views:131 Category:PHP
-
This article shows the steps to update the PHP version from 7.x version to 7.4 in CentOS. How to Update PHP from 7.X to 7.4 in CentOS Update operating system packages. yum update -y Check your PHP version in CentOS. php -v Prints a list of