AccessToken.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php namespace App\Servers\Encrypts;
  2. use Firebase\JWT\JWT;
  3. use Firebase\JWT\Key;
  4. /**
  5. * 登录令牌
  6. *
  7. * @author 刘相欣
  8. */
  9. class AccessToken
  10. {
  11. protected $config;
  12. public function __construct()
  13. {
  14. // 过期时间
  15. $expire = (int) config('login_expire_day',30);
  16. // 默认时间
  17. $expire = $expire ? $expire : 7;
  18. // 配置
  19. $this->config = [
  20. 'alg'=>'HS256',
  21. 'key'=> config('PWD_KEY','123456789@abcdedfghlk'),
  22. 'expire_interval' => $expire * 86400,
  23. 'login_expire_day' => $expire,
  24. ];
  25. }
  26. /**
  27. * 加密数据
  28. *
  29. * @param array $data 数据
  30. * @return string 返回结果
  31. *
  32. */
  33. public function encode( array $data ){
  34. return JWT::encode( $data, $this->config['key'], $this->config['alg'] );
  35. }
  36. /**
  37. * 解密数据
  38. *
  39. * @param string $access_token 加密数据
  40. * @return array 返回结果
  41. *
  42. */
  43. public function decode( string $access_token ){
  44. try{
  45. $access_token_data = (array) JWT::decode( $access_token, new Key($this->config['key'],$this->config['alg']));
  46. } catch( \Firebase\JWT\ExpiredException $e ){
  47. return ['error'=>$e->getMessage()];
  48. } catch( \Firebase\JWT\SignatureInvalidException $e ){
  49. return ['error'=>$e->getMessage()];
  50. } catch( \Exception $e ){
  51. return ['error'=>$e->getMessage()];
  52. }
  53. return $access_token_data;
  54. }
  55. /**
  56. * 生成权限令牌
  57. *
  58. *
  59. */
  60. public function createAccessToken( int $user_id, int $start_time = 0 )
  61. {
  62. // 组合数据
  63. $encodeData = [
  64. 'jti' => $start_time,
  65. // 'iss' => '',
  66. 'sub' => $user_id,
  67. 'company_id'=>request('company_id',0),
  68. 'iat' => $start_time,
  69. 'exp' => $start_time + $this->config['expire_interval'],
  70. ];
  71. // 生成权限令牌
  72. $access_token = $this->encode( $encodeData );
  73. // 返回结果
  74. return [
  75. 'access_token' => $access_token,
  76. 'expires_in' => $encodeData['exp'],
  77. ];
  78. }
  79. }