簡體   English   中英

Symfony 3 - 內容安全策略

[英]Symfony 3 - Content Security Policy

我的內容安全策略有問題。 每當我嘗試將JavaScript包含到我的項目中時,我都會收到內容安全策略錯誤。

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

我究竟做錯了什么?

我已經嘗試過了:

好的,我找到了解決方案。 我在代碼中添加了一個事件訂閱者,它設置了“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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM