feat: api endpoints

This commit is contained in:
Björn Fromme
2024-12-04 14:18:47 +01:00
parent 7379f5ac93
commit 231aaaac9b
26 changed files with 606 additions and 43 deletions
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class ApiKeyAuthenticator extends AbstractAuthenticator
{
public function __construct(private readonly array $apiKeys)
{
}
public function supports(Request $request): ?bool
{
return $request->headers->has('X-BPN-API-KEY');
}
public function authenticate(Request $request): Passport
{
$apiKey = $request->headers->get('X-BPN-API-KEY');
if (null === $apiKey) {
throw new CustomUserMessageAuthenticationException('No API key provided');
}
if (false === in_array($apiKey, $this->apiKeys)) {
throw new CustomUserMessageAuthenticationException('Invalid API key');
}
return new SelfValidatingPassport(
new UserBadge($apiKey, function (string $userIdentifier) use ($apiKey): ?UserInterface {
return new ApiUser($apiKey);
})
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$data = [
'message' => 'Authentication missing or failed',
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class ApiUser implements UserInterface
{
public function __construct(private readonly string $apiKey)
{
}
public function getRoles(): array
{
return ['ROLE_USER', 'ROLE_API'];
}
public function eraseCredentials(): void
{
}
public function getUserIdentifier(): string
{
return $this->apiKey;
}
}