thinkphp5框架API token身份验证功能示例
本文实例讲述了thinkphp5框架APItoken身份验证功能。分享给大家供大家参考,具体如下:
使用说明:登陆时生成token和刷新用的refresh_token,返回给客户端,客户端收到保存本地localStorage等,每次访问接口带上token,后端验证token存在并且一致后方可执行接下来的动作,假如不存在就返回token过期,客户端调用刷新接口传入token和refresh_token,服务器端进行验证,验证通过重新生成新的token保存数据库,返回给客户端客户端刷新本地token访问即可继续,当refresh_token验证失败就清除数据库token,过期时间等信息
简单的token生成函数(公共函数文件common)
functioncreate_token($id,$out_time){ returnsubstr(md5($id.$out_time),5,26); }
验证登陆方法(模型)
publicfunctioncheckLogin($username,$passwd){ $driver=self::field('driver_id,passwd')->where('zhanghao',$username)->whereOr('phone',$username)->find(); if(empty($driver)){ $this->error='账号不存在'; returnfalse; } if($driver['passwd']!=md5($passwd)){ $this->error="密码不正确"; returnfalse; } //$out_time=strtotime('+1days'); $out_time=strtotime('+1minutes'); $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='登陆失败'; returnfalse; } $refresh_token_out_time=strtotime('+5days'); $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刷新方法(模型)
publicfunctionrefreshToken($refresh_token,$token){ if(!isset(Cache::get('refresh_token'))orCache::get('refresh_token')!=$refresh_token){ $this->error='刷新token失败'; returnfalse; } $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='参数错误'; returnfalse; } $out_time=strtotime('+1days');//新的过期时间 $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='刷新失败'; returnfalse; } Cache::set("token",$token,864000); return['token'=>$token,'in_expire'=>$out_time]; }
退出方法(模型)
publicfunctionlogout($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'); }
更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《ZendFrameWork框架入门教程》及《PHP模板技术总结》。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。