CheckAuth.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace app\common\middleware;
  3. use Exception;
  4. use thans\jwt\exception\TokenInvalidException;
  5. use thans\jwt\facade\JWTAuth;
  6. //验证权限
  7. class CheckAuth
  8. {
  9. public function handle($request, \Closure $next)
  10. {
  11. try {
  12. $jwtData = JWTAuth::auth();
  13. } catch (Exception $exception) {
  14. //token有误
  15. if (get_class($exception) == TokenInvalidException::class) {
  16. return shutdown('登陆信息有误 请重新登录', -1);
  17. }
  18. $errorMsgArr = [
  19. 'Must have token' => '请先登陆系统',
  20. 'The token is in blacklist.' => '登陆已失效 请重新登陆',
  21. 'The token is expired.' => '登陆已过期 请重新登陆',
  22. 'The token is in blacklist grace period list.' => '登陆已过期 请重新登陆'
  23. ];
  24. return shutdown($errorMsgArr[$exception->getMessage()] ?? $exception->getMessage(), -1);
  25. }
  26. $userInfo = $jwtData['info']->getValue();
  27. //解密token中的用户信息
  28. $userInfo = str_encipher($userInfo,false, config('app.aes_token_key'));
  29. if (!$userInfo) {
  30. return shutdown('用户信息有误,请重新登陆', -1);
  31. }
  32. //解析json
  33. $userInfo = (array)json_decode($userInfo, true);
  34. //已经登陆,将用户信息存入请求头
  35. $request->userInfo = $userInfo;
  36. $request->uid = $userInfo['id'];
  37. $request->userToken = JWTAuth::token()->get();
  38. return $next($request);
  39. }
  40. }