2

我对内容安全策略有疑问。每当我尝试将 JavaScript 包含到我的项目中时,都会收到内容安全策略错误。

<!DOCTYPE html>
<html>
    <head>
        <title>Symfony</title>
        <script src="{{ asset('myscript.js') }}"></script>
    </head>
    <body>
      // ...
    </body>
</html>

我究竟做错了什么?

我已经尝试过:

4

1 回答 1

5

好的,我找到了解决方案。我在我的代码中添加了一个事件订阅者,它设置了“Content-Security-Policy”标头。

<?php

namespace AppBundle\Subscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class ResponseSubscriber
 * @package AppBundle\Subscriber
 */
class ResponseSubscriber implements EventSubscriberInterface
{
    /** @inheritdoc */
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => 'onResponse'
        ];
    }

    /**
     * Callback function for event subscriber
     * @param FilterResponseEvent $event
     */
    public function onResponse(FilterResponseEvent $event)
    {
        $response = $event->getResponse();

        $policy = "default-src 'self' 'unsafe-inline';"
            . "script-src 'self' 'unsafe-inline'";

        $response->headers->set("Content-Security-Policy", $policy);
        $response->headers->set("X-Content-Security-Policy", $policy);
        $response->headers->set("X-WebKit-CSP", $policy);
    }
}

# app/config/services.yml
services:
    # ...
    app.responseSubscriber:
        class: AppBundle\Subscriber\ResponseSubscriber
        autowire: true
于 2018-02-15T13:16:50.513 回答