You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace jwt;
class Jwt
{
private $key = '!@#$%*&^*';
/**
* 签发Token
* @param array $info 自定义信息,不要定义敏感信息
* @param int $time_out 过期时间
* @date 2020-09-03
*/
public function signToken($info = [], $time_out = 86400 * 30)
{
$key = $this->key;
$time = time(); //当前时间
$token = [
"iss" => '', //签发者 可选
"aud" => '', //接收该JWT的一方可选
"iat" => $time, //签发时间
"nbf" => $time, //(Not Before)某个时间点后才能访问比如设置time+30表示当前时间30秒后才能使用
"exp" => $time + $time_out, //token 过期时间
"data" => $info //自定义信息,不要定义敏感信息
];
$jwt = \Firebase\JWT\JWT::encode($token, $key); //输出Token
$token['token'] = $jwt;
return $token;
}
/**
* 验证Token
* @param string $token Token
* @date 2020-09-03
*/
public function checkToken($token)
{
$key = $this->key;
try {
\Firebase\JWT\JWT::$leeway = 60; //当前时间减去60把时间留点余地
$decoded = \Firebase\JWT\JWT::decode($token, $key, ['HS256']); //HS256方式这里要和签发的时候对应
$arr = objectToArray($decoded);
return ['code' => 0, 'data' => $arr, 'msg' => ''];
} catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
return ['code' => -1, 'data' => [], 'msg' => $e->getMessage()];
} catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
return ['code' => -2, 'data' => [], 'msg' => $e->getMessage()];
} catch (\Firebase\JWT\ExpiredException $e) { // token过期
return ['code' => -3, 'data' => [], 'msg' => $e->getMessage()];
} catch (\Exception $e) { //其他错误
return ['code' => -4, 'data' => [], 'msg' => $e->getMessage()];
}
//Firebase定义了多个 throw new我们可以捕获多个catch来定义问题catch加入自己的业务比如token过期可以用当前Token刷新一个新Token
}
}