<?php
namespace App\Security\Firewall;
use App\Security\Authentication\Token\OAuthToken;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class OAuthListener
{
protected TokenStorageInterface $tokenStorage;
protected AuthenticationManagerInterface $authenticationManager;
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager)
{
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
}
public function __invoke(RequestEvent $event): void
{
if (!$this->supports($event->getRequest())) {
return;
}
$token = new OAuthToken();
$token->setToken($this->getCredentials($event->getRequest()));
$authToken = $this->authenticationManager->authenticate($token);
$this->tokenStorage->setToken($authToken);
}
public function getCredentials(Request $request): ?string
{
$authorizationHeader = $request->headers->get('Authorization');
$headerToken = substr($authorizationHeader, 7); // remove 'Bearer '
// @todo access_token is used for backwards compatibility, remove in the future if possible.
return $headerToken ?? $request->request->get('access_token');
}
public function supports(Request $request): bool
{
// @todo access_token is used for backwards compatibility, remove in the future if possible.
return str_starts_with($request->headers->get('Authorization'), 'Bearer ') || $request->get('access_token');
}
}