JwtBaseController.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace app\common\controller;
  3. use Firebase\JWT\JWT;
  4. use Firebase\JWT\Key;
  5. use app\BaseController;
  6. use app\common\util\Result;
  7. use EasyWeChatComposer\EasyWeChat;
  8. use app\common\exception\CatchException;
  9. class JwtBaseController extends BaseController
  10. {
  11. protected $failException = true;
  12. /**
  13. * $key jwt HS256 key
  14. *
  15. * @var string
  16. */
  17. protected $key;
  18. /**
  19. * $table 当前使用的表
  20. *
  21. * @var mixed
  22. */
  23. protected $table;
  24. /**
  25. * $model 当前使用的模型
  26. *
  27. * @var \think\Model
  28. */
  29. protected $model;
  30. /**
  31. * $wechat 微信小程序api实例
  32. *
  33. * @var \EasyWeChat\MiniProgram\Application
  34. */
  35. private static $_wechat;
  36. /**
  37. * 设置jwt密钥
  38. *
  39. * @param mixed $key
  40. *
  41. * @return void
  42. */
  43. protected function setKey($key) {
  44. $this->key = $key;
  45. }
  46. /**
  47. * 验证token
  48. *
  49. * @return void
  50. */
  51. public function valid()
  52. {
  53. // 允许 Authorization 头部通过 cors
  54. $jwt = $this->request->header('Authorization');
  55. if (empty($jwt)) {
  56. throw new CatchException("未授权用户", 600);
  57. }
  58. $jwt = str_replace('Bearer ', '', $jwt);
  59. // try decode
  60. $this->decodeJwt($jwt);
  61. return Result::rest(true);
  62. }
  63. /**
  64. * 默认参数
  65. *
  66. * @return mixed
  67. */
  68. protected function params($validator = null, $name = '')
  69. {
  70. $params = $this->request->param($name, null, 'trim');
  71. // 尝试校验
  72. if (!is_null($validator)) {
  73. $this->validate($params, $validator);
  74. }
  75. return $params;
  76. }
  77. protected function only(array $names)
  78. {
  79. return $this->request->only($names);
  80. }
  81. /**
  82. * encodeJwt
  83. *
  84. * @param array|\stdClass $payload
  85. *
  86. * @return string
  87. */
  88. protected function encodeJwt($payload)
  89. {
  90. return JWT::encode($payload, $this->key, 'HS256');
  91. }
  92. /**
  93. * decodeJwt
  94. *
  95. * @param string $jwt
  96. *
  97. * @return \stdClass
  98. */
  99. protected function decodeJwt($jwt)
  100. {
  101. return JWT::decode($jwt, new Key($this->key, 'HS256'));
  102. }
  103. }