一、准备
两台服务器:
一台前端html服务器 http://admin.tp_mall.com
一台后端获取数据及redis数据库服务器 http://api.tp_mall.com
后端php框架:thinkphp5.1
jsonp
二、流程及原理
用户登录页 http://admin.tp_mall.com/login/login.html
ajax表单提交登录
登录成功将id、uname、usalt、logintime通过aes对称加密生成token
将token写入redis数据库(设置过期时间)
ajax返回token及用户名和头像(便于显示)、并且写入cookie
跳转首页并发送携带token的ajax请求数据
新建一个tp框架中间件adminlogincheck.php 拦截http请求来判断是否登录
token有效且未过期表示已登录,通过中间件到达控制器返回数据给页面
刷新redis中的logintime维持登录状态
token无效或已过期标识未登录,返回状态并重定向到登录页
三、主要代码
adminlogincheck中间件主要代码
public function handle($request, closure $next)
{
$jsonp = $request->param('callback');
$token = $request->param('token');
$aes = new aes('zyddj123');
$tokenvalue = $aes->decrypt($token);
$tokenarr = explode(' ', $tokenvalue);
$key = 'admintoken_'.$tokenarr[0];
$redis = new redis();
$redistoken = $redis->get($key);
$redistokenvalue = $aes->decrypt($redistoken);
$redistokenarr = explode(' ', $redistokenvalue);
if ($redistokenarr[0] == $tokenarr[0] && $redistokenarr[1] == $tokenarr[1] && $redistokenarr[2] == $tokenarr[2] && intval($redistokenarr[count($redistokenarr) - 1]) + 7200 > time()) {
//已经登录 刷新redis中token过期时间
$redistokenarr[count($redistokenarr) - 1] = time();
$newtoken = $aes->encrypt(implode(' ', $redistokenarr));
if (!$redis->set($key, $newtoken, 7200)) {
$ret = [
'sta' => -2,
'mes' => '写入redis中token过期时间失败!',
];
echo $jsonp.'('.json_encode($ret).')';
die;
}
} else {
//未登录 终止程序
$ret = [
'sta' => -1,
'mes' => '请重新登录!',
];
echo $jsonp.'('.json_encode($ret).')';
die;
}
return $next($request);
}
设置redis过期时间
/**
* 设置用户token的redis过期时间
*
* @param [type] $info 用户身份信息
* @return $token or false
*/
public static function setredisexpire($info)
{
$aes = new aes('zyddj123');
$redis = new redis();
$tokenvalue = [
'id'=>$info['id'],
'uname'=>$info['uname'],
'usalt'=>$info['usalt'],
'logintime'=>time()
];
$token = $aes->encrypt(implode( ,$tokenvalue));
$key = 'admintoken_'.$info['id'];
return $redis->set($key,$token,7200)?$token:false;
}
四、详细
详细请移步至我的github
(前端)https://github.com/zyddj123/mall_html
(后端)https://github.com/zyddj123/tp_mall
网络推广的过程中要注意哪些内容?小企业仍然可以在SEO上取得成功渭南营销型网站建设中不同的网页导航企业网站推广在百度贴吧发帖怎么样效果最好?有哪些注意事项?设计公司网站时对颜色的配比B2B网站的运营思路(定位篇)网站改版后应该怎么做SEO优化?网站建设中需要注意哪些小细节呢?