Skip to content

Instantly share code, notes, and snippets.

@pzsprog
Last active March 31, 2020 20:58
Show Gist options
  • Save pzsprog/81f6272fbdf4eca81401a3a221405927 to your computer and use it in GitHub Desktop.
Save pzsprog/81f6272fbdf4eca81401a3a221405927 to your computer and use it in GitHub Desktop.
Symfony CORS pre-flight kernel listener (with authorization)
<?php
// https://www.upbeatproductions.com/blog/cors-pre-flight-requests-and-headers-symfony-httpkernel-component
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpFoundation\Response;
class CorsListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array('onKernelRequest', 9999),
KernelEvents::RESPONSE => array('onKernelResponse', 9999),
);
}
public function onKernelRequest(RequestEvent $event)
{
// Don't do anything if it's not the master request.
if (!$event->isMasterRequest())
{
return;
}
$request = $event->getRequest();
$method = $request->getRealMethod();
if ('OPTIONS' == $method)
{
$response = new Response('dasd');
$event->setResponse($response);
}
}
public function onKernelResponse(ResponseEvent $event)
{
// Don't do anything if it's not the master request.
if (!$event->isMasterRequest()) {
return;
}
$response = $event->getResponse();
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET,POST,PUT');
$response->headers->set('Access-Control-Allow-Headers', 'authorization');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment