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