同时使用 NWebSec.Mvc 和 NWebSec.OWIN 时,是否需要在 2 个地方配置安全性?

When using both NWebSec.Mvc and NWebSec.OWIN, do I need to configue security in 2 places?

我有一个使用 ASP.NET Identity v2 的 ASP.NET MVC 5 站点。我正在尝试使用 NWebSec 到 "harden" 它。

因为网站使用 MVC 和 Owin,所以我安装了 NWebSec.MVC 和 NWebSec.OWIN NuGet 包。

阅读文档,可以通过配置文件为 NWebSec/MVC 设置许多选项,并且可以通过 [=39] 在代码中为 NWebSec.OWIN 设置一些相同的选项=] 文件。

例如,要添加HSTS,我可以在web.config中执行以下操作:

  <nwebsec>
    <httpHeaderSecurityModule xmlns="http://nwebsec.com/HttpHeaderSecurityModuleConfig.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="NWebsecConfig/HttpHeaderSecurityModuleConfig.xsd">
      <securityHttpHeaders>
        <strict-Transport-Security max-age="365" includeSubdomains="true" httpsOnly="false" preload="true" />
      </securityHttpHeaders>
    </httpHeaderSecurityModule>
  </nwebsec>

...and/or startup.cs 中的以下内容:

    public void Configuration(IAppBuilder app)
    {
        this.ConfigureAuth(app);

        app.UseHsts(o => o.MaxAge(365).IncludeSubdomains().AllResponses().Preload());
    }

我的问题是:我是否必须在两个地方都设置所有选项 - 或者只在一个地方(在这种情况下哪个更好)?

我更愿意在 web.config 文件中进行所有配置,但我不确定这是否会遗漏一些需要在 Startup.cs 文件中设置的内容。

您可以安全地设置web.config中的所有配置。 OWIN 包适用于那些喜欢使用启动 class 而不是 web.config.

的人

如果你应该配置例如web.config 和中间件中的 HSTS,header 将首先根据 web.config 在响应中设置。中间件稍后将在管道中 运行,并根据 OWIN 配置设置 header,而不考虑 web.config 中的内容。因此,当在两个地方都配置 headers 时,中间件获胜。

为了这个答案的完整性:如果您使用 MVC 属性覆盖基本​​配置,则在计算结果配置时,将选择特定 header 的 OWIN 配置而不是 web.config。所以 OWIN 在所有情况下都胜过 web.config。