在登录erp的时候,想要通过点击的方式,直接登录到另外一个网站。
也就是登录A网站,点击一个进入B网站的连接,B网站直接就是登录状态,不需要登录了。
test: http://www.xxx.com/test.php?usercode=10014&username=zhao usercode唯一
1.
首先A登录的时候通过api获取key,设置超时时间为10秒
$remoteDomain = "http://market.fancyecommerce.com"; $username = 'admin'; $key = "dsf2djdp3"; $url = $remoteDomain."/fecadmin/login/remoteindex?key=".$key."&username=".$username; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT,10); $data = curl_exec($ch); curl_close($ch);通过上面的代码回去B网站获取access_token信息。
2.B网站的代码:
2.1 安全验证key,以及参数是否存在
2.2 本地数据库查找用户,如果没有,则新建一个用户。
2.3 随机生成一个新的accessToken, 保存
2.4 返回生成的accessToken
public function getCurrentUser($username,$usercode){ $user = AdminUser::findOne(['username' => $username]); if($user->username){ }else{ $adminUser = new AdminUser; $adminUser->username = $username; $adminUser->code = $usercode; $adminUser->setPassword(md5(CDate::getCurrentDateTime())); //$adminUser->save(); $user = AdminUser::findOne(['username' => $username]); } $user->generateAccessToken(); $user->save(); return $user; } # 通过远程,获取当前用户的access_token # 传递username usercode(可选) # 返回json格式的access_token public function actionRemoteindex(){ $key = CRequest::param("key"); $configKey = CConfig::param("remote_get_access_token_key"); $username = CRequest::param("username"); $usercode = CRequest::param("usercode") ? CRequest::param("usercode") : ''; if(($configKey) && ($key == $configKey) && $username){ $user = $this->getCurrentUser($username,$usercode); if(isset($user['access_token'])) echo json_encode(["access_token" =>$user['access_token']]); } }
现在回到A网站,下面是完成代码:
<?php $remoteDomain = "http://market.fancyecommerce.com"; $username = 'admin'; $key = "dsf2ddp3"; $url = $remoteDomain."/fecadmin/login/remoteindex?key=".$key."&username=".$username; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT,10); $data = curl_exec($ch); curl_close($ch); if($data){ $arr = json_decode($data,true); $access_token = $arr['access_token']; $url = $remoteDomain."/fecadmin/login/loginbyaccesstoken?access_token=".$access_token."&username=".$username; } ?> <a target="_blank" href="<?= $url ?>">Data WEBSite</a>
4.点击这个链接跳转到b网站。B网站验证这个access_token是否有效
如果有效,则设置当前用户为登录状态。跳转到用户的dashboard界面
代码如下:
# 通过access_token 设置登录状态 public function actionLoginbyaccesstoken(){ $access_token = CRequest::param("access_token"); $username = CRequest::param("username"); if($access_token ){ if($username){ $one = AdminUser::findOne([ 'username' => $username, 'access_token' => $access_token, ]); if($one->username){ $one->generateAccessToken(); $one->save(); \Yii::$app->user->login($one, 3600 * 24); header('Location: '.CUrl::getHomeUrl()); }else{ echo "User Access Token Is TimeOut"; } }else{ echo "UserName Can Not Empty"; } }else{ echo "Access Token Can Not Empty"; } }