| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <?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',30);
- // 默认时间
- $expire = $expire ? $expire : 7;
- // 配置
- $this->config = [
- 'alg'=>'HS256',
- 'key'=> config('PWD_KEY','123456789@abcdedfghlk'),
- 'expire_interval' => $expire * 86400,
- 'login_expire_day' => $expire,
- ];
- }
- /**
- * 加密数据
- *
- * @param array $data 数据
- * @return string 返回结果
- *
- */
- public function encode( array $data ){
- return JWT::encode( $data, $this->config['key'], $this->config['alg'] );
- }
- /**
- * 解密数据
- *
- * @param string $access_token 加密数据
- * @return array 返回结果
- *
- */
- 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,
- 'company_id'=>request('company_id',0),
- 'iat' => $start_time,
- 'exp' => $start_time + $this->config['expire_interval'],
- ];
- // 生成权限令牌
- $access_token = $this->encode( $encodeData );
- // 返回结果
- return [
- 'access_token' => $access_token,
- 'expires_in' => $encodeData['exp'],
- ];
- }
- }
|