hash_do($h . $p . md5($this->KEY), $header['alg']); $sign = $h. '.' . $p . '.' . $s; return $sign; } return null; } public function check_token($jwt){ if (empty($jwt)){ return false; } $tokens = explode('.', $jwt); if (count($tokens)!==3){ return false; } list($header64, $payload64, $sign) = $tokens; $header = json_decode(base64_decode($header64), TRUE); if (!isset($header['alg'])){ return false; } $s = $this->hash_do($header64 . $payload64 . md5($this->KEY), $header['alg']); if ($s !== $sign){ return false; } $payload = json_decode(base64_decode($payload64), TRUE); $time = time(); if (isset($payload['iat']) && $payload['iat'] > $time){ return false; } if (isset($payload['exp']) && $payload['exp'] < $time){ return false; } return true; } }
使用式:
public function auth_token(){ $over = config('TOKEN_OVER_TIME'); // 生存时间 $time = time(); $time_over = $time + $over; $header = [ 'typ' => 'JWT', 'alg' => 'HS256' ]; $payload = [ 'iss' => 'admin_name', 'iat' => $time, 'exp' => $time_over, 'uid' => 12 ]; $j = new Jwt(); $sign = $j->create_token($header, $payload); return $sign; } public function check(){ $jwt = 'jwtxxxxxxxx'; $j = new Jwt(); $b = $j->check_token($jwt); dump($b); }