thinkPHP5.1接口使用token进行验证
2023-03-29 23:03:03
208
{{single.collect_count}}

1.创建token,生成一个唯一的字符串,在用户登录的时候返回,使用其他方式也可以

//创建tokenstatic public function MakeToken(){$str = md5(uniqid(md5(microtime(true)), true)); //创建唯一token$str = sha1($str);return $str;}
2.下面的直接贴上代码,逻辑是在接口公共类上把token放在初始化方法里验证,其余的放在代码注释里了
<?phpnamespace app\api\controller;use think\App;use think\Controller;use think\Db;use think\Request;use think\Response;use clt\Encryption;/** * 接口公共类 * @package app\api\controller */class Common extends Controller{protected $user_id = NULL,$encryption = null;protected $noNeedLogin = ['login']; //不需要验证的接口public function initialize(){header('Content-Type: text/html;charset=utf-8');header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型$this->encryption = new Encryption();$token=\request()->header('token');//从header里获取tokenif ($this->noNeedLogin){ //检查不需要token验证的接口$controller=request()->action();if (in_array($controller,$this->noNeedLogin)){return true;}}//检查token$this->CheckToken($token);}/** * 检查token */public function CheckToken($token){if($token){$res = Db::name('user')->field('id,expires_time')->where(['token'=>$token])->where('expires_time','>',time())->find();if ($res){$this->user_id = $res['id'];//更新token,到期十分钟更新if($res['expires_time']-time() <= 10*60){$expires_time = $res['expires_time']+7200;Db::name('user')->where('id',$res['id'])->update(['expires_time'=>$expires_time]);}}else{$rs_arr['code'] = 500;$rs_arr['msg']="登录已过期,请重新登录";$rs_arr['data']=null;Response::create($rs_arr, 'json')->send();exit;}}else{$rs_arr['code']=500;$rs_arr['msg']='请先登录';$rs_arr['data']=null;Response::create($rs_arr, 'json')->send();exit;}}}

 

3.此方法还需要不断完善,如刷新token等,暂时采用token快到期,操作进行token延期,也可以使用第三方的接口验证工具,如JWT

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}