add basic authentication with user, password and api key

This commit is contained in:
2026-07-17 16:05:28 +02:00
parent d90c5887fc
commit 956aff9fe3
4 changed files with 37 additions and 9 deletions
+20 -8
View File
@@ -15,20 +15,32 @@ class ApiTokenAuthenticator
public function authenticate(Request $request): void
{
$authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
if (!$authorization) {
$authorizationHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
if (!$authorizationHeader) {
throw new \Exception('Missing Authorization header');
}
if (!preg_match('/^Bearer\s+(.*)$/i', trim($authorization), $matches)) {
// Basic authorization formal test
if (!preg_match('/^Basic\s+(.*)$/i', trim($authorizationHeader), $matches)) {
throw new \Exception('Invalid Authorization header format');
}
// Username and password test
$decoded = explode(':', base64_decode($matches[1]), 2);
$authorized = empty(array_diff([ $this->config->secret('api_access_username'), $this->config->secret('api_access_password')], $decoded));
if (!$authorized) {
throw new \Exception('Authorization failed');
}
$token = $matches[1];
$expected = $this->config->secret('api_access_token');
if (empty($expected) || !hash_equals((string) $expected, (string) $token)) {
throw new \Exception('Invalid API access token');
// Now, for the X-API-Key only if it was defined in the config (simple way to disable it for testing)
$expectedApiKey = $this->config->secret('api_access_token');
if ($expectedApiKey !== null && trim($expectedApiKey) !== '') {
$apiKeyHeader = $_SERVER['HTTP_X_API_KEY'] ?? $_SERVER['REDIRECT_HTTP_X_API_KEY'] ?? '';
if (!$apiKeyHeader) {
throw new \Exception('Missing API access token');
}
if (!hash_equals((string) $expectedApiKey, (string) $apiKeyHeader)) {
throw new \Exception('Invalid API access token');
}
}
}
}
+11
View File
@@ -8,4 +8,15 @@ class Response {
echo json_encode($data);
exit;
}
public function unauthorized(?string $data = null) {
http_response_code(401);
header('Content-Type: application/json');
header('HTTP/1.1 401 Unauthorized');
header('Content-Length: 0');
if ($data !== null && $data !== '') {
echo json_encode($data);
}
exit;
}
}