You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.4 KiB
68 lines
2.4 KiB
<?php
|
|
namespace App\Security;
|
|
|
|
use App\Repository\UserRepository;
|
|
use Psr\Log\LoggerInterface;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
|
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
|
|
use Symfony\Component\Security\Core\Exception\AuthenticationException;
|
|
use Symfony\Component\Security\Core\User\UserInterface;
|
|
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
|
|
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
|
|
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
|
|
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
|
|
|
|
class ApiKeyAuthenticator extends AbstractAuthenticator
|
|
{
|
|
|
|
public function __construct(private UserRepository $userRepository, private LoggerInterface $logger)
|
|
{}
|
|
|
|
/**
|
|
* Called on every request to decide if this authenticator should be
|
|
* used for the request.
|
|
* Returning false will cause this authenticator
|
|
* to be skipped.
|
|
*/
|
|
public function supports(Request $request): ?bool
|
|
{
|
|
return $request->headers->has('X-AUTH-TOKEN');
|
|
}
|
|
|
|
public function authenticate(Request $request): Passport
|
|
{
|
|
$apiToken = $request->headers->get('X-AUTH-TOKEN');
|
|
if (null === $apiToken) {
|
|
return null;
|
|
}
|
|
|
|
$userIdentifier = $apiToken;
|
|
|
|
return new SelfValidatingPassport(
|
|
new UserBadge($userIdentifier,
|
|
function (string $userIdentifier): ?UserInterface {
|
|
return $this->userRepository->findOneBy([
|
|
'authName' => $userIdentifier
|
|
]);
|
|
}));
|
|
}
|
|
|
|
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
|
|
{
|
|
// on success, let the request continue
|
|
return null;
|
|
}
|
|
|
|
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
|
|
{
|
|
$this->logger->critical("YYY");
|
|
$message = strtr($exception->getMessageKey(), $exception->getMessageData());
|
|
// or to translate this message
|
|
// $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
|
|
|
|
// This should translated by FOSRestBundle!
|
|
throw new AccessDeniedHttpException($message);
|
|
}
|
|
} |