1 安装
~~~
composer require firebase/php-jwt
~~~
2 用法
~~~
use \Firebase\JWT\JWT;
$key = "example_key";
$token = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1356999524,
"nbf" => 1357000000
);
$jwt = JWT::encode($token, $key);
$decoded = JWT::decode($jwt, $key, array('HS256'));
print_r($decoded);
$decoded_array = (array) $decoded;
JWT::$leeway = 60; // $leeway in seconds
$decoded = JWT::decode($jwt, $key, array('HS256'));
~~~
3 补充捕获异常
~~~
try {
$arr = $jwt::decode($token, $key, array('HS256'));
} catch (\Exception $e) { // token验证失败
return json(['code' => 0, 'msg' => $e->getMessage()],400)->send();
}catch (ExpiredException $e){ // 过期
return json(['code' => 0, 'msg' => $e->getMessage()],400)->send();
}
~~~
