InnerApiAuthMiddleware.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * 内部API AUTH中间件.
  4. */
  5. namespace Modules\InnerApi\Middlewares;
  6. use App\Exceptions\InnerApiException;
  7. use Closure;
  8. use Illuminate\Support\Str;
  9. class InnerApiAuthMiddleware
  10. {
  11. /**
  12. * 排除认证的路由.
  13. * @var string[]
  14. */
  15. protected $except = [
  16. ];
  17. /**
  18. * Handle an incoming request.
  19. *
  20. * @param \Illuminate\Http\Request $request
  21. * @param \Closure $next
  22. * @return mixed
  23. */
  24. public function handle($request, Closure $next)
  25. {
  26. if (!$this->shouldPassThrough($request)) {
  27. $xToken = $request->header('X-TOKEN', '');
  28. $tokenSecret = env('INNERT_API_TOKEN_SECRET', Str::random(6));
  29. if ($xToken !== $tokenSecret) {
  30. throw new InnerApiException('认证错误', 403);
  31. }
  32. }
  33. return $next($request);
  34. }
  35. /**
  36. * 获取排除项.
  37. * @return array
  38. */
  39. public function getExcept()
  40. {
  41. return $this->except;
  42. }
  43. /**
  44. * Determine if the request has a URI that should pass through CSRF verification.
  45. *
  46. * @param \Illuminate\Http\Request $request
  47. * @return bool
  48. */
  49. protected function shouldPassThrough($request)
  50. {
  51. foreach ($this->getExcept() as $except) {
  52. if ($except !== '/') {
  53. $except = trim($except, '/');
  54. }
  55. if ($request->is($except)) {
  56. return true;
  57. }
  58. }
  59. return false;
  60. }
  61. }