123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- <?php namespace App\Servers\Encrypts;
- use Firebase\JWT\JWT;
- use Firebase\JWT\Key;
- /**
- * 登录令牌
- *
- * @author 刘相欣
- */
- class AccessToken
- {
- protected $config;
- public function __construct()
- {
- // 过期时间
- $expire = (int) config('login_expire_day',7);
- // 默认时间
- $expire = $expire ? $expire : 7;
- // 配置
- $this->config = [
- // 'iss' => '',
- 'alg' => 'HS256',
- 'key' => config('PWD_KEY','123456789@abcdedfghlk'),
- 'expire_interval' => $expire * 24 * 60 * 60,
- 'login_expire_day' => $expire,
- ];
- }
- /**
- * 加密数据
- *
- */
- public function encode( array $data )
- {
- return JWT::encode( $data, $this->config['key'], $this->config['alg'] );
- }
- /**
- * 解密数据
- *
- */
- public function decode( string $access_token )
- {
- try{
- $access_token_data = (array) JWT::decode( $access_token, new Key($this->config['key'],$this->config['alg']));
- } catch( \Firebase\JWT\ExpiredException $e ){
- return ['error'=>$e->getMessage()];
- } catch( \Firebase\JWT\SignatureInvalidException $e ){
- return ['error'=>$e->getMessage()];
- } catch( \Exception $e ){
- return ['error'=>$e->getMessage()];
- }
- return $access_token_data;
- }
- /**
- * 生成权限令牌
- *
- *
- */
- public function createAccessToken( int $user_id, int $start_time = 0 )
- {
- // 组合数据
- $encodeData = [
- 'jti' => $start_time,
- // 'iss' => '',
- 'sub' => $user_id,
- 'iat' => $start_time,
- 'exp' => $start_time + $this->config['expire_interval'],
- ];
- // 生成权限令牌
- $access_token = $this->encode( $encodeData );
- // 返回结果
- return [
- 'access_token' => $access_token,
- 'expires_in' => $encodeData['exp'],
- ];
- }
- }
|