<?php
declare(strict_types=1);
namespace App\Infrastructure\Auth\Symfony\Security\Authenticator;
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\BadCredentialsException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
class SiteAuthenticator extends AbstractAuthenticator implements LoggerAwareInterface
{
use LoggerAwareTrait;
/**
* Paths under the /api firewall that are PUBLIC_ACCESS (see security.yaml)
* and must never be routed through site Basic-auth, regardless of what
* Authorization header (if any) the caller happens to send.
*/
private const PUBLIC_PATH_PATTERNS = [
'#^/api/docs#',
'#^/api/direct-debit#',
'#^/api/recurring-payments#',
'#^/api/finxp-callback#',
];
public function supports(Request $request): ?bool
{
foreach (self::PUBLIC_PATH_PATTERNS as $pattern) {
if (preg_match($pattern, $request->getPathInfo()) === 1) {
return false;
}
}
return $request->headers->has('Authorization');
}
public function authenticate(Request $request): Passport
{
$header = (string) $request->headers->get('Authorization', '');
$username = null;
$password = null;
if (str_starts_with(strtolower($header), 'basic')) {
$decoded = base64_decode(trim(substr($header, 6)), true);
$basic = $decoded !== false ? explode(':', $decoded, 2) : [];
$username = $basic[0] ?? null;
$password = $basic[1] ?? null;
}
if ($username === null || $password === null) {
throw new BadCredentialsException('Missing or malformed Authorization header.');
}
return new Passport(new UserBadge($username), new PasswordCredentials($password));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$this->logger->error('Merchant authentication failed: ' . $exception->getMessage());
return new JsonResponse([
'error' => 'Authorization required',
'error_code' => 401,
], Response::HTTP_UNAUTHORIZED);
}
}