PHP、TP5使用JWT做接口验证

加密方式使用php的password_hash()方法,自认为安全性不错


/**
 * Class JWT
 * 接口验证类
 */

class JWT{
	private $key;
	//构造函数
	function __construct($key)
	{
		$this->key = $key;
	}
	//创建jwt
	public function creat_jwt($data){
		$hear['alg']='password_hash';//加密方式
		$hear['typ']='JWT';
		$data['jwt_iss']=$_SERVER['SERVER_ADDR'];
		$data['jwt_aud']='lzy';
		$data['jwt_start_time']=time();
		$data['jwt_end_time']=time()+86400*30;
		$sign['hear']=$hear;
		$sign['data']=$data;
		return base64_encode(json_encode($hear,320)).'..'.base64_encode(json_encode($data,320)).'..'.password_hash(base64_encode(json_encode($sign,320)),PASSWORD_DEFAULT);
	}
	//检查jwt格式是否错误
	public function check_jwt($jwt){
		$jwt=explode('..',$jwt);
		if(count($jwt)!=3){
			return ['code'=>-1,'msg'=>'JWT格式错误'];
		}
		$hear=json_decode(base64_decode($jwt[0]),true);
		$data=json_decode(base64_decode($jwt[1]),true);
		if(!is_json(base64_decode($jwt[0])) || !is_json(base64_decode($jwt[1]))){
			return ['code'=>-1,'msg'=>'JWT格式错误'];
		}
		$sign['hear']=$hear;
		$sign['data']=$data;
		$sign=base64_encode(json_encode($sign,320));
		if($data['jwt_end_time']<time()){
			return ['code'=>-2,'msg'=>'JWT已过时'];
		}else{
			if(!password_verify($sign,$jwt[2])){
				return ['code'=>-1,'msg'=>'JWT内容错误'];
			}else{
				return ['code'=>1,'msg'=>'JWT验证成功'];
			}
		}
	}
	//解析jwt的数据
	public function trans_data($jwt){
	    $result=$this->check_jwt($jwt);
		if($result['code']!=1){
			return ['code'=>-1,'msg'=>$result['msg']];
		}
		$jwt=explode('..',$jwt);
		$data=json_decode(base64_decode($jwt[1]),true);
		return ['code'=>1,'msg'=>'解析成功','data'=>$data];
	}
}



你可能感兴趣的:(tp5,php)