AccessToken.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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',7);
  16. // 默认时间
  17. $expire = $expire ? $expire : 7;
  18. // 配置
  19. $this->config = [
  20. // 'iss' => '',
  21. 'alg' => 'HS256',
  22. 'key' => config('PWD_KEY','123456789@abcdedfghlk'),
  23. 'expire_interval' => $expire * 24 * 60 * 60,
  24. 'login_expire_day' => $expire,
  25. ];
  26. }
  27. /**
  28. * 加密数据
  29. *
  30. */
  31. public function encode( array $data )
  32. {
  33. return JWT::encode( $data, $this->config['key'], $this->config['alg'] );
  34. }
  35. /**
  36. * 解密数据
  37. *
  38. */
  39. public function decode( string $access_token )
  40. {
  41. try{
  42. $access_token_data = (array) JWT::decode( $access_token, new Key($this->config['key'],$this->config['alg']));
  43. } catch( \Firebase\JWT\ExpiredException $e ){
  44. return ['error'=>$e->getMessage()];
  45. } catch( \Firebase\JWT\SignatureInvalidException $e ){
  46. return ['error'=>$e->getMessage()];
  47. } catch( \Exception $e ){
  48. return ['error'=>$e->getMessage()];
  49. }
  50. return $access_token_data;
  51. }
  52. /**
  53. * 生成权限令牌
  54. *
  55. *
  56. */
  57. public function createAccessToken( int $user_id, int $start_time = 0 )
  58. {
  59. // 组合数据
  60. $encodeData = [
  61. 'jti' => $start_time,
  62. // 'iss' => '',
  63. 'sub' => $user_id,
  64. 'iat' => $start_time,
  65. 'exp' => $start_time + $this->config['expire_interval'],
  66. ];
  67. // 生成权限令牌
  68. $access_token = $this->encode( $encodeData );
  69. // 返回结果
  70. return [
  71. 'access_token' => $access_token,
  72. 'expires_in' => $encodeData['exp'],
  73. ];
  74. }
  75. }