<?php
namespace App\EventSubscriber;
use App\Twig\NonceGenerator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class XSSProtector implements EventSubscriberInterface
{
/** @var NonceGenerator $nonceGenerator */
private $nonceGenerator;
public function __construct(NonceGenerator $nonceGenerator)
{
// inject the nonce generator service we created in previous steps
$this->nonceGenerator = $nonceGenerator;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
// listen to the kernel.response event
return [KernelEvents::RESPONSE => 'addCSPHeaderToResponse'];
}
/**
* Adds the Content Security Policy header.
*
* @param ResponseEvent $event
*/
public function addCSPHeaderToResponse(ResponseEvent $event)
{
// get the Response object from the event
$response = $event->getResponse();
// create a CSP rule, using the nonce generator service
$nonce = $this->nonceGenerator->getNonce();
$cspHeader = "script-src 'nonce-" . $nonce . "' 'unsafe-eval' 'strict-dynamic' https: http:;";
// set CPS header on the response object
$response->headers->set("Content-Security-Policy", $cspHeader);
$response->headers->set("X-Content-Type-Options", 'nosniff');
}
}