后端开发
网络新概念,云计算、大数据、O2O、电商。。。。
网络新概念,云计算、大数据、O2O、电商。。。。
2019-01-15 16:53:58
php中实现jwt的token
参考文档:https://segmentfault.com/a/1190000009981879
$payload=[ 'exp' => $_SERVER['REQUEST_TIME'] + 7200, //过期时间 'uid'=>1111, 'uname'=>'张三' ]; $key='ddddd'; $utoken=token_encode($payload,$key); echo $utoken; function token_encode(array $payload, string $key, string $alg = 'SHA256') { $key = md5($key); $jwt = urlsafeB64Encode(json_encode(['typ' => 'JWT', 'alg' => $alg])) . '.' . urlsafeB64Encode(json_encode($payload)); return $jwt . '.' . signature($jwt, $key, $alg); } function signature(string $input, string $key, string $alg) { return hash_hmac($alg, $input, $key); } function token_decode(string $jwt, string $key) { $tokens = explode('.', $jwt); $key = md5($key); if (count($tokens) != 3) return false; list($header64, $payload64, $sign) = $tokens; $header = json_decode(urlsafeB64Decode($header64), JSON_OBJECT_AS_ARRAY); if (empty($header['alg'])) return false; if (signature($header64 . '.' . $payload64, $key, $header['alg']) !== $sign) return false; $payload = json_decode(urlsafeB64Decode($payload64), JSON_OBJECT_AS_ARRAY); $time = $_SERVER['REQUEST_TIME']; if (isset($payload['iat']) && $payload['iat'] > $time) return false; if (isset($payload['exp']) && $payload['exp'] < $time) return false; return $payload; } function urlsafeB64Decode(string $input) { $remainder = strlen($input) % 4; if ($remainder) { $padlen = 4 - $remainder; $input .= str_repeat('=', $padlen); } return base64_decode(strtr($input, '-_', '+/')); } function urlsafeB64Encode(string $input) { return str_replace('=', '', strtr(base64_encode($input), '+/', '-_')); }
上一篇:php记录用户访问信息的方法