Symfony 中的 Nonce 和 Web 开发人员工具栏

lio*_*elp 5 php security symfony

Symfony 在开发 Web 工具栏中使用随机数,如下所示:

<div id="sfwdtd61de8" class="sf-toolbar sf-display-none"></div><script 
nonce=ca6666b27bc9c402c16192e4b43bbdaa>
Run Code Online (Sandbox Code Playgroud)

等等,然后,由于随机数是动态生成的,我不能在我的虚拟主机中使用这种内容安全策略代码:

Header set Content-Security-Policy script-src 'self' 'nonce-
ca6666b27bc9c402c16192e4b43bbdaa'
Run Code Online (Sandbox Code Playgroud)

那么我应该怎么做才能将 Web 开发人员工具栏代码列入白名单呢?

我在用着 :

  • 交响乐3.3.2
  • 阿帕奇2.4.25
  • PHP 7.1.2

Dav*_*sek 1

创建订阅者:

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;

class NonceSubscriber implements EventSubscriberInterface
{
    private $tokenGenerator;
    
    public function __construct( TokenGeneratorInterface $tokenGenerator ) 
    {
        $this->tokenGenerator = $tokenGenerator;
    }
    
    public function onKernelResponse(ResponseEvent $event)
    {    
        $response = $event->getResponse();

        $token_CSRF = $this->tokenGenerator->generateToken();
        
        $response->headers->set
        (
            'Content-Security-Policy', "script-src nonce-".$token_CSRF."';"
        );
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => 'onKernelResponse',
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

之后,您将$token_CSRF在响应标头中看到您的随机数以及由 WebProfilerBundle 生成的随机数。