div>
2020-8-11 214 0
PHP

JWT类库<?php/***PHP实现jwt*/classJwt{//头部privatestatic$header=array('alg'=>'HS256',//生成signature的算法'typ'=>'JWT'//类型);//使用HMAC生成信息摘要时所使用的密钥privatestatic$key='mini!@!@^@^$%#$--*$#@(*)&&*Bingpo';/***获取jwttoken*@paramarray$payloadjwt载荷格式如下非必须*[*'iss'=>'jwt_admin',//该JWT的签发者*'iat'=>time(),//签发时间*'exp'=>time()+7200,//过期时间*'nbf'=>time()+60,//该时间之前不接收处理该Token*'sub'=>'www.admin.com',//面向的用户*'jti'=>md5(uniqid('JWT').time())//该Token唯一标识*]*@returnbool|string*/publicstaticfunctiongetToken(array$payload){if(is_array($payload)){$base64header=self::base64UrlEncode(json_encode(self::$header,JSON_UNESCAPED_UNICODE));$base64payload=self::base64UrlEncode(json_encode($payload,JSON_UNESCAPED_UNICODE));$token=$base64header.'.'.$base64payload.'.'.self::signature($base64header.'.'.$base64payload,self::$key,self::$header['alg']);return$token;}else{returnfalse;}}/***验证token是否有效,默认验证exp,nbf,iat时间*@paramstring$Token需要验证的token*@returnbool|string*/publicstaticfunctionverifyToken(string$Token){$tokens=explode('.',$Token);if(count($tokens)!=3)returnfalse;list($base64header,$base64payload,$sign)=$tokens;//获取jwt算法$base64decodeheader=json_decode(self::base64UrlDecode($base64header),JSON_OBJECT_AS_ARRAY);if(empty($base64decodeheader['alg']))returnfalse;//签名验证if(self::signature($base64header.'.'.$base64payload,self::$key,$base64decodeheader['alg'])!==$sign)returnfalse;$payload=json_decode(self::base64UrlDecode($base64payload),JSON_OBJECT_AS_ARRAY);//签发时间大于当前服务器时间验证失败if(isset($payload['iat'])&&$payload['iat']>time())returnfalse;//过期时间小宇当前服务器时间验证失败if(isset($payload['exp'])&&$payload['exp']<time())returnfalse;//该nbf时间之前不接收处理该Tokenif(isset($payload['nbf'])&&$payload['nbf']>time())returnfalse;return$payload;}/***base64UrlEncodehttps://jwt.io/中base64UrlEncode编码实现*@paramstring$input需要编码的字符串*@returnstring*/privatestaticfunctionbase64UrlEncode(string$input){returnstr_replace('=','',strtr(base64_encode($input),'+/','-_'));}/***base64UrlEncodehttps://jwt.io/中base64UrlEncode解码实现*@paramstring$input需要解码的字符串*@returnbool|string*/privatestaticfunctionbase64UrlDecode(string$input){$remainder=strlen($input)%4;if($remainder){$addlen=4-$remainder;$input.=str_repeat('=',$addlen);}returnbase64_decode(strtr($input,'-_','+/'));}/***HMACSHA256签名https://jwt.io/中HMACSHA256签名实现*@paramstring$input为base64UrlEncode(header).".".base64UrlEncode(payload)*@paramstring$key*@paramstring$alg算法方式*@returnmixed*/privatestaticfunctionsignature(string$input,string$key,string$alg='HS256'){$alg_config=array('HS256'=>'sha256');returnself::base64UrlEncode(hash_hmac($alg_config[$alg],$input,$key,true));}}调用方法引入之后用下面方法使用签发token$payload_test=array('iss'=>'Bingpo','iat'=>time(),'exp'=>time()+21600,'nbf'=>time(),'sub'=>'5','jti'=>md5(uniqid('JWT').time()));$token_test=Jwt::getToken($payload_test);echo$token_test;验证token$getPayload_test=Jwt::verifyToken($token_test);var_dump($getPayload_test);这是我见过最简单的php封装的库,不像别的看着繁琐的一批!

2020-7-9 324 0