AuthTokenMiddleware.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\http\middleware\api;
  12. use app\Request;
  13. use app\services\user\UserAuthServices;
  14. use Closure;
  15. use Psr\SimpleCache\InvalidArgumentException;
  16. use qiniu\exceptions\AuthException;
  17. use qiniu\interfaces\MiddlewareInterface;
  18. /**
  19. * Class AuthTokenMiddleware
  20. * @package app\api\middleware
  21. */
  22. class AuthTokenMiddleware implements MiddlewareInterface
  23. {
  24. /**
  25. * @param Request $request
  26. * @param Closure $next
  27. * @param bool $force
  28. * @return mixed|object
  29. * @throws InvalidArgumentException
  30. */
  31. public function handle(Request $request, Closure $next, bool $force = true)
  32. {
  33. $authInfo = null;
  34. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  35. if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  36. try {
  37. /** @var UserAuthServices $service */
  38. $service = app()->make(UserAuthServices::class);
  39. $authInfo = $service->parseToken($token);
  40. } catch (AuthException $e) {
  41. if ($force)
  42. return app('json')->make($e->getCode(), $e->getMessage());
  43. }
  44. if (!is_null($authInfo)) {
  45. $request->setUser($authInfo['user']);
  46. $request->setTokenData($authInfo['tokenData']);
  47. }
  48. return $next($request);
  49. }
  50. }