Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
CORS Listener and Handling with Symfony2
<?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class CorsListener
{
public function __construct(array $options)
{
$this->cors = $options;
}
public function onKernelRequest(GetResponseEvent $event)
{
// Don't do anything if it's not the master request.
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
$method = $request->getRealMethod();
// perform preflight checks
if ('OPTIONS' === $request->getMethod()) {
$response = new Response();
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization');
$response->headers->set('Access-Control-Max-Age', 3600);
//$response->headers->set('Access-Control-Allow-Origin', '*');
$event->setResponse($response);
return;
}
}
public function onKernelResponse(FilterResponseEvent $event)
{
$request = $event->getRequest();
// Run CORS check in here to ensure domain is in the system
if (in_array($request->headers->get('origin'), $this->cors)) {
$response = $event->getResponse();
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization');
$response->headers->set('Access-Control-Allow-Origin', $corsOrigin);
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
$response->headers->set('Vary', 'Origin');
$event->setResponse($response);
}
return;
}
}
...
<service id="app.tokens.action_listener" class="AppBundle\EventListener\CorsListener">
<argument>%app_bundle.cors.origins%</argument>
<tag name="kernel.event_listener" event="kernel.controller" method="onKernelController" />
<tag name="kernel.event_listener" event="kernel.response" method="onKernelResponse" />
<tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" priority="300" />
</service>
...

Hello.
First, what's the parameter value for %app_bundle.cors.origins%,
and second, i don't understand why do you have event kernel.controller for onKernelController method, when you don't have that method in your CorsListener class in the first place?
Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment