ApiAuthMiddleware.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. namespace App\Module\OpenAPI\Middleware;
  3. use App\Module\OpenAPI\Services\OpenApiService;
  4. use App\Module\OpenAPI\Services\AuthService;
  5. use App\Module\OpenAPI\Enums\AUTH_TYPE;
  6. use Closure;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Http\Response;
  9. /**
  10. * API认证中间件
  11. */
  12. class ApiAuthMiddleware
  13. {
  14. /**
  15. * @var OpenApiService
  16. */
  17. protected OpenApiService $openApiService;
  18. /**
  19. * @var AuthService
  20. */
  21. protected AuthService $authService;
  22. public function __construct(OpenApiService $openApiService, AuthService $authService)
  23. {
  24. $this->openApiService = $openApiService;
  25. $this->authService = $authService;
  26. }
  27. /**
  28. * 处理请求
  29. *
  30. * @param Request $request
  31. * @param Closure $next
  32. * @param string|null $scope
  33. * @return mixed
  34. */
  35. public function handle(Request $request, Closure $next, string $scope = null)
  36. {
  37. try {
  38. // 获取认证信息
  39. $authInfo = $this->extractAuthInfo($request);
  40. if (!$authInfo) {
  41. return $this->unauthorizedResponse('缺少认证信息');
  42. }
  43. // 验证应用
  44. $app = $this->validateApp($authInfo);
  45. if (!$app) {
  46. return $this->unauthorizedResponse('应用认证失败');
  47. }
  48. // 检查权限范围
  49. if ($scope && !$this->openApiService->checkScope($app, $scope)) {
  50. return $this->forbiddenResponse('权限不足');
  51. }
  52. // 检查IP白名单
  53. if (!$this->openApiService->checkIpWhitelist($app, $request->ip())) {
  54. return $this->forbiddenResponse('IP地址不在白名单中');
  55. }
  56. // 将应用信息添加到请求中
  57. $request->attributes->set('openapi_app', $app);
  58. $request->attributes->set('openapi_auth_type', $authInfo['type']);
  59. // 更新最后使用时间
  60. $this->openApiService->updateLastUsed($app);
  61. return $next($request);
  62. } catch (\Exception $e) {
  63. return $this->errorResponse('认证过程中发生错误: ' . $e->getMessage());
  64. }
  65. }
  66. /**
  67. * 提取认证信息
  68. *
  69. * @param Request $request
  70. * @return array|null
  71. */
  72. protected function extractAuthInfo(Request $request): ?array
  73. {
  74. // API Key认证
  75. if ($apiKey = $this->extractApiKey($request)) {
  76. return [
  77. 'type' => AUTH_TYPE::API_KEY,
  78. 'app_id' => $apiKey['app_id'],
  79. 'app_secret' => $apiKey['app_secret'],
  80. ];
  81. }
  82. // Bearer Token认证
  83. if ($token = $this->extractBearerToken($request)) {
  84. return [
  85. 'type' => AUTH_TYPE::BEARER,
  86. 'token' => $token,
  87. ];
  88. }
  89. // Basic认证
  90. if ($basic = $this->extractBasicAuth($request)) {
  91. return [
  92. 'type' => AUTH_TYPE::BASIC,
  93. 'app_id' => $basic['username'],
  94. 'app_secret' => $basic['password'],
  95. ];
  96. }
  97. // 签名认证
  98. if ($signature = $this->extractSignature($request)) {
  99. return [
  100. 'type' => AUTH_TYPE::SIGNATURE,
  101. 'app_id' => $signature['app_id'],
  102. 'signature' => $signature['signature'],
  103. 'timestamp' => $signature['timestamp'],
  104. ];
  105. }
  106. return null;
  107. }
  108. /**
  109. * 提取API Key
  110. *
  111. * @param Request $request
  112. * @return array|null
  113. */
  114. protected function extractApiKey(Request $request): ?array
  115. {
  116. $headerName = config('openapi.auth.api_key.header_name', 'X-API-Key');
  117. $queryParam = config('openapi.auth.api_key.query_param', 'api_key');
  118. // 从Header获取
  119. $apiKey = $request->header($headerName);
  120. // 从Query参数获取
  121. if (!$apiKey) {
  122. $apiKey = $request->query($queryParam);
  123. }
  124. if (!$apiKey) {
  125. return null;
  126. }
  127. // 解析API Key格式:app_id:app_secret
  128. if (strpos($apiKey, ':') !== false) {
  129. list($appId, $appSecret) = explode(':', $apiKey, 2);
  130. return [
  131. 'app_id' => $appId,
  132. 'app_secret' => $appSecret,
  133. ];
  134. }
  135. // 如果只有一个值,尝试从数据库查找
  136. return [
  137. 'app_id' => $apiKey,
  138. 'app_secret' => null,
  139. ];
  140. }
  141. /**
  142. * 提取Bearer Token
  143. *
  144. * @param Request $request
  145. * @return string|null
  146. */
  147. protected function extractBearerToken(Request $request): ?string
  148. {
  149. $authorization = $request->header('Authorization');
  150. if (!$authorization || !str_starts_with($authorization, 'Bearer ')) {
  151. return null;
  152. }
  153. return substr($authorization, 7);
  154. }
  155. /**
  156. * 提取Basic认证
  157. *
  158. * @param Request $request
  159. * @return array|null
  160. */
  161. protected function extractBasicAuth(Request $request): ?array
  162. {
  163. $authorization = $request->header('Authorization');
  164. if (!$authorization || !str_starts_with($authorization, 'Basic ')) {
  165. return null;
  166. }
  167. $credentials = base64_decode(substr($authorization, 6));
  168. if (strpos($credentials, ':') === false) {
  169. return null;
  170. }
  171. list($username, $password) = explode(':', $credentials, 2);
  172. return [
  173. 'username' => $username,
  174. 'password' => $password,
  175. ];
  176. }
  177. /**
  178. * 提取签名认证
  179. *
  180. * @param Request $request
  181. * @return array|null
  182. */
  183. protected function extractSignature(Request $request): ?array
  184. {
  185. $signatureHeader = config('openapi.auth.signature.header_name', 'X-Signature');
  186. $timestampHeader = config('openapi.auth.signature.timestamp_header', 'X-Timestamp');
  187. $signature = $request->header($signatureHeader);
  188. $timestamp = $request->header($timestampHeader);
  189. $appId = $request->header('X-App-Id');
  190. if (!$signature || !$timestamp || !$appId) {
  191. return null;
  192. }
  193. return [
  194. 'app_id' => $appId,
  195. 'signature' => $signature,
  196. 'timestamp' => $timestamp,
  197. ];
  198. }
  199. /**
  200. * 验证应用
  201. *
  202. * @param array $authInfo
  203. * @return \App\Module\OpenAPI\Models\OpenApiApp|null
  204. */
  205. protected function validateApp(array $authInfo)
  206. {
  207. switch ($authInfo['type']) {
  208. case AUTH_TYPE::API_KEY:
  209. case AUTH_TYPE::BASIC:
  210. return $this->authService->validateApiKey(
  211. $authInfo['app_id'],
  212. $authInfo['app_secret']
  213. );
  214. case AUTH_TYPE::BEARER:
  215. return $this->authService->validateBearerToken($authInfo['token']);
  216. case AUTH_TYPE::SIGNATURE:
  217. return $this->authService->validateSignature(
  218. $authInfo['app_id'],
  219. $authInfo['signature'],
  220. $authInfo['timestamp'],
  221. request()
  222. );
  223. default:
  224. return null;
  225. }
  226. }
  227. /**
  228. * 返回未授权响应
  229. *
  230. * @param string $message
  231. * @return Response
  232. */
  233. protected function unauthorizedResponse(string $message): Response
  234. {
  235. return response()->json([
  236. 'error' => 'Unauthorized',
  237. 'message' => $message,
  238. 'code' => 401,
  239. ], 401);
  240. }
  241. /**
  242. * 返回禁止访问响应
  243. *
  244. * @param string $message
  245. * @return Response
  246. */
  247. protected function forbiddenResponse(string $message): Response
  248. {
  249. return response()->json([
  250. 'error' => 'Forbidden',
  251. 'message' => $message,
  252. 'code' => 403,
  253. ], 403);
  254. }
  255. /**
  256. * 返回错误响应
  257. *
  258. * @param string $message
  259. * @return Response
  260. */
  261. protected function errorResponse(string $message): Response
  262. {
  263. return response()->json([
  264. 'error' => 'Internal Server Error',
  265. 'message' => $message,
  266. 'code' => 500,
  267. ], 500);
  268. }
  269. }