以下由thinkphp教學專欄跟大家介紹【範例】thinkphp5框架API token身分驗證功能,希望對需要的朋友有幫助!
使用說明:登陸時產生token和刷新用的refresh_token,返回給客戶端,客戶端收到保存本地localStorage等,每次訪問接口帶上token,後端驗證token存在且一致後方可執行接下來的動作,假如不存在就返回token過期,客戶端呼叫刷新介面傳入token和refresh_token,伺服器端進行驗證,驗證透過重新產生新的token保存資料庫,返回給予客戶端用戶端刷新本地token存取即可繼續,當refresh_token驗證失敗就清除資料庫token,過期時間等資訊
簡單的token產生函數(公用函數檔common)
function create_token($id,$out_time){ return substr(md5($id.$out_time),5,26); }
驗證登陸方法(模型)
public function checkLogin($username,$passwd){ $driver = self::field('driver_id,passwd')->where('zhanghao',$username)->whereOr('phone',$username)->find(); if (empty($driver)){ $this->error = '账号不存在'; return false; } if ($driver['passwd'] != md5($passwd)){ $this->error = "密码不正确"; return false; } //$out_time = strtotime('+ 1 days'); $out_time = strtotime('+ 1 minutes'); $token = create_token($driver['driver_id'],$out_time); if(false===self::save(['token'=>$token,'time_out'=>$out_time],['driver_id'=>$driver['driver_id']])){ $this->error = '登陆失败'; return false; } $refresh_token_out_time = strtotime('+ 5 days'); $refresh_token = create_token($driver['driver_id'],$refresh_token_out_time); Cache::set("token",$token,60); Cache::set("driver_id",$driver['driver_id'],$refresh_token_out_time);//设置ID的过期时间和更新token的token时间一样用于更新的时候获取用户信息 Cache::set('refresh_token',$refresh_token,$refresh_token_out_time); return ['token'=>$token,'refresh_token'=>$refresh_token,'in_expire'=>$out_time]; }
token刷新方法(模型)
public function refreshToken($refresh_token,$token){ if (!isset(Cache::get('refresh_token')) or Cache::get('refresh_token')!=$refresh_token){ $this->error = '刷新token失败'; return false; } $cache_driver_id = Cache::get('driver_id'); $driver = self::field('driver_id,passwd')->where('driver_id',$cache_driver_id)->where('token',$token)->find(); if (empty($driver)){ $this->error = '参数错误'; return false; } $out_time = strtotime('+ 1 days');//新的过期时间 $token = create_token($driver['driver_id'],$out_time);//更新token if(false===self::save(['token'=>$token,'time_out'=>$out_time],['driver_id'=>$driver['driver_id']])){ Cache::clear($token); $this->error = '刷新失败'; return false; } Cache::set("token",$token,864000); return ['token'=>$token,'in_expire'=>$out_time]; }
#退出方法(模型)
public function logout($token,$refresh_token=''){ $driver = self::field('driver_id,passwd')->where('token',$token)->find(); self::save(['token'=>'','time_out'=>''],['token'=>$token]); Cache::clear('token'); Cache::clear('refresh_token'); }
以上是thinkphp5框架API token身分驗證功能【範例】的詳細內容。更多資訊請關注PHP中文網其他相關文章!