JwtAuthMiddleware.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace app\admin\middleware;
  3. use app\admin\model\SystemAdmin;
  4. use Tinywan\Jwt\Exception\JwtTokenException;
  5. use Tinywan\Jwt\JwtToken;
  6. use Webman\Http\Response;
  7. use Webman\Http\Request;
  8. use Webman\MiddlewareInterface;
  9. /**
  10. * 登录验证中间件
  11. * Class JwtAuthMiddleware
  12. * @package app\admin\middleware
  13. */
  14. class JwtAuthMiddleware implements MiddlewareInterface
  15. {
  16. public function process(Request $request, callable $next): Response
  17. {
  18. if ($request->method() === 'OPTIONS') {
  19. response('', 204);
  20. }
  21. try {
  22. $token = $request->header('Authorization');
  23. if (strpos($token, 'Bearer') === 0){
  24. $token = trim(substr($token, 6));
  25. }
  26. if(!$token)
  27. {
  28. throw new JwtTokenException('请登录', 500);
  29. }
  30. $rest = JwtToken::verify(1, $token);
  31. $request->admin_id = JwtToken::getCurrentId();
  32. $request->admin_token = $token;
  33. $request->admin_info = SystemAdmin::getAdminInfo($request->admin_id);
  34. return $next($request);
  35. } catch (JwtTokenException $e) {
  36. throw new JwtTokenException($e->getMessage(), $e->getCode());
  37. }
  38. }
  39. }