src/App/Security/Firewall/OAuthListener.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\Security\Firewall;
  3. use App\Security\Authentication\Token\OAuthToken;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  7. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  8. class OAuthListener
  9. {
  10.     protected TokenStorageInterface $tokenStorage;
  11.     protected AuthenticationManagerInterface $authenticationManager;
  12.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationManagerInterface $authenticationManager)
  13.     {
  14.         $this->tokenStorage $tokenStorage;
  15.         $this->authenticationManager $authenticationManager;
  16.     }
  17.     public function __invoke(RequestEvent $event): void
  18.     {
  19.         if (!$this->supports($event->getRequest())) {
  20.             return;
  21.         }
  22.         $token = new OAuthToken();
  23.         $token->setToken($this->getCredentials($event->getRequest()));
  24.         $authToken $this->authenticationManager->authenticate($token);
  25.         $this->tokenStorage->setToken($authToken);
  26.     }
  27.     public function getCredentials(Request $request): ?string
  28.     {
  29.         $authorizationHeader $request->headers->get('Authorization');
  30.         $headerToken substr($authorizationHeader7); // remove 'Bearer '
  31.         // @todo access_token is used for backwards compatibility, remove in the future if possible.
  32.         return $headerToken ?? $request->request->get('access_token');
  33.     }
  34.     public function supports(Request $request): bool
  35.     {
  36.         // @todo access_token is used for backwards compatibility, remove in the future if possible.
  37.         return str_starts_with($request->headers->get('Authorization'), 'Bearer ') || $request->get('access_token');
  38.     }
  39. }