为什么web.config中的Content-Security-Policy设置不起作用?

时间:2018-07-10 09:32:49

标签: asp.net-mvc content-security-policy

在一个小型的ASP.NET MVC测试应用程序中,我按照this article中的描述向httpProtocol文件中添加了适当的web.config代码:

  <system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
      <httpProtocol>
          <customHeaders>
              <add name="Content-Security-Policy" value="default-src 'self'" />
          </customHeaders>
      </httpProtocol>
  </system.webServer>

但是,在应用程序的测试页上,Vue.js代码仍然有效,由于它是从CDN加载的,因此内容安全策略应将其阻止。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page2 - Meine ASP.NET-Anwendung</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.6.2.js"></script>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
</head>
<body>
    <div class="container mainMenu">
        <ul>
            <li><a href="/">Start Page</a></li>
            <li><a href="/Home/About">About</a></li>
            <li><a href="/Home/Contact">Contact</a></li>
            <li><a href="/Home/Info">Info</a></li>
        </ul>
    </div>
    <div class="container body-content">
        <hr/>



<div id="app">
    this is a test: <b>{{message}}</b>
</div>


<script>

    var app = new Vue({
        el: '#app',
        data: {
            message: 'Vue.js ready'
        }
    });
</script>
        <hr/>
        <footer>
            <p>The footer</p>
        </footer>
    </div>

    <script src="/Scripts/jquery-1.10.2.js"></script>

    <script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>


</body>
</html>

我该怎么做才能使内容安全策略在我的网站中真正生效?

附录

我可以在开发工具中看到,响应头中没有发送Content-Security-Policy:

enter image description here

1 个答案:

答案 0 :(得分:0)

看到下面问题中的配置块,让我假设您已将<httpProtocol><customHeaders> ...部分添加到web.config文件夹中的Views文件中,而不是web.config文件中在您网站的根目录中。

<system.webServer>
    <handlers>
        <remove name="BlockViewHandler"/>
        <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
</system.webServer>