IpWhitelistMiddleware.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. namespace App\Module\OpenAPI\Middleware;
  3. use App\Module\OpenAPI\Models\OpenApiApp;
  4. use Closure;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Log;
  7. /**
  8. * IP白名单中间件
  9. *
  10. * 用于验证请求IP是否在应用的白名单中
  11. */
  12. class IpWhitelistMiddleware
  13. {
  14. /**
  15. * 处理请求
  16. *
  17. * @param Request $request
  18. * @param Closure $next
  19. * @return mixed
  20. */
  21. public function handle(Request $request, Closure $next)
  22. {
  23. // 获取应用信息
  24. $app = $this->getAppFromRequest($request);
  25. if (!$app) {
  26. return $this->forbiddenResponse('应用信息不存在');
  27. }
  28. // 检查IP白名单
  29. if (!$this->checkIpWhitelist($app, $request->ip())) {
  30. return $this->forbiddenResponse('IP地址不在白名单中');
  31. }
  32. // 记录IP检查日志
  33. $this->logIpCheck($app, $request);
  34. return $next($request);
  35. }
  36. /**
  37. * 从请求中获取应用信息
  38. *
  39. * @param Request $request
  40. * @return OpenApiApp|null
  41. */
  42. protected function getAppFromRequest(Request $request): ?OpenApiApp
  43. {
  44. // 从请求属性中获取应用信息(由认证中间件设置)
  45. return $request->attributes->get('openapi_app');
  46. }
  47. /**
  48. * 检查IP白名单
  49. *
  50. * @param OpenApiApp $app
  51. * @param string $ip
  52. * @return bool
  53. */
  54. protected function checkIpWhitelist(OpenApiApp $app, string $ip): bool
  55. {
  56. // 获取应用的IP白名单配置
  57. $ipWhitelist = $app->ip_whitelist ?? [];
  58. // 如果没有配置白名单,默认允许所有IP
  59. if (empty($ipWhitelist)) {
  60. return true;
  61. }
  62. // 检查IP是否在白名单中
  63. foreach ($ipWhitelist as $allowedIp) {
  64. if ($this->matchIp($ip, $allowedIp)) {
  65. return true;
  66. }
  67. }
  68. return false;
  69. }
  70. /**
  71. * 匹配IP地址
  72. *
  73. * @param string $ip 请求IP
  74. * @param string $pattern IP模式(支持CIDR、通配符等)
  75. * @return bool
  76. */
  77. protected function matchIp(string $ip, string $pattern): bool
  78. {
  79. // 精确匹配
  80. if ($ip === $pattern) {
  81. return true;
  82. }
  83. // CIDR格式匹配(如:192.168.1.0/24)
  84. if (str_contains($pattern, '/')) {
  85. return $this->matchCidr($ip, $pattern);
  86. }
  87. // 通配符匹配(如:192.168.1.*)
  88. if (str_contains($pattern, '*')) {
  89. return $this->matchWildcard($ip, $pattern);
  90. }
  91. // 范围匹配(如:192.168.1.1-192.168.1.100)
  92. if (str_contains($pattern, '-')) {
  93. return $this->matchRange($ip, $pattern);
  94. }
  95. return false;
  96. }
  97. /**
  98. * CIDR格式匹配
  99. *
  100. * @param string $ip
  101. * @param string $cidr
  102. * @return bool
  103. */
  104. protected function matchCidr(string $ip, string $cidr): bool
  105. {
  106. list($subnet, $mask) = explode('/', $cidr);
  107. $ipLong = ip2long($ip);
  108. $subnetLong = ip2long($subnet);
  109. $maskLong = -1 << (32 - (int)$mask);
  110. return ($ipLong & $maskLong) === ($subnetLong & $maskLong);
  111. }
  112. /**
  113. * 通配符匹配
  114. *
  115. * @param string $ip
  116. * @param string $pattern
  117. * @return bool
  118. */
  119. protected function matchWildcard(string $ip, string $pattern): bool
  120. {
  121. // 将通配符转换为正则表达式
  122. $regex = str_replace(['*', '.'], ['[0-9]+', '\.'], $pattern);
  123. $regex = '/^' . $regex . '$/';
  124. return preg_match($regex, $ip) === 1;
  125. }
  126. /**
  127. * 范围匹配
  128. *
  129. * @param string $ip
  130. * @param string $range
  131. * @return bool
  132. */
  133. protected function matchRange(string $ip, string $range): bool
  134. {
  135. list($start, $end) = explode('-', $range);
  136. $ipLong = ip2long($ip);
  137. $startLong = ip2long(trim($start));
  138. $endLong = ip2long(trim($end));
  139. return $ipLong >= $startLong && $ipLong <= $endLong;
  140. }
  141. /**
  142. * 记录IP检查日志
  143. *
  144. * @param OpenApiApp $app
  145. * @param Request $request
  146. * @return void
  147. */
  148. protected function logIpCheck(OpenApiApp $app, Request $request): void
  149. {
  150. Log::info("IP whitelist check passed", [
  151. 'app_id' => $app->app_id,
  152. 'ip' => $request->ip(),
  153. 'whitelist' => $app->ip_whitelist,
  154. 'uri' => $request->getRequestUri(),
  155. 'method' => $request->getMethod(),
  156. 'user_agent' => $request->userAgent(),
  157. ]);
  158. }
  159. /**
  160. * 返回IP被拒绝响应
  161. *
  162. * @param string $message
  163. * @return \Illuminate\Http\JsonResponse
  164. */
  165. protected function forbiddenResponse(string $message)
  166. {
  167. return response()->json([
  168. 'error' => 'ip_not_allowed',
  169. 'message' => $message,
  170. ], 403);
  171. }
  172. }