1.创建token,生成一个唯一的字符串,在用户登录的时候返回,使用其他方式也可以
//创建token
static public function MakeToken(){
$str = md5(uniqid(md5(microtime(true)), true)); //创建唯一token
$str = sha1($str);
return $str;
}
2.下面的直接贴上代码,逻辑是在接口公共类上把token放在初始化方法里验证,其余的放在代码注释里了
<?php
namespace 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里获取token
if ($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