Files
dafuweng-saiadmin6.x/server/app/api/middleware/ApiKeyMiddleware.php

65 lines
1.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\api\middleware;
use app\api\util\ReturnCode;
use plugin\saiadmin\exception\ApiException;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
/**
* 校验对接平台 api-key与 .env 中 API_KEY 一致)
* 仅用于 /api/v1/* 平台对接接口
*
* 取值优先级(按顺序读取,首个非空即采用):
* 1. 请求头 api-key推荐
* 2. 查询参数 api_key / api-key
* 3. body 表单/JSON api_key / api-key
*/
class ApiKeyMiddleware implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$expected = (string) config('api.platform_api_key', '');
if ($expected === '') {
throw new ApiException('API_KEY is not configured', ReturnCode::SERVER_ERROR);
}
$apiKey = $this->resolveApiKey($request);
if ($apiKey === '') {
throw new ApiException('Please provide api-key', ReturnCode::UNAUTHORIZED);
}
if (!hash_equals($expected, $apiKey)) {
throw new ApiException('Invalid api-key', ReturnCode::FORBIDDEN);
}
return $handler($request);
}
private function resolveApiKey(Request $request): string
{
$headerValue = $request->header('api-key');
if ($headerValue !== null && trim((string) $headerValue) !== '') {
return trim((string) $headerValue);
}
foreach (['api_key', 'api-key'] as $key) {
$val = $request->get($key);
if ($val !== null && trim((string) $val) !== '') {
return trim((string) $val);
}
}
foreach (['api_key', 'api-key'] as $key) {
$val = $request->post($key);
if ($val !== null && trim((string) $val) !== '') {
return trim((string) $val);
}
}
return '';
}
}