Search code examples
asp.net-mvcsecurityowinhstsnwebsec

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


I have an ASP.NET MVC 5 site that uses ASP.NET Identity v2. I'm trying to use NWebSec to "harden" it.

Because the site uses MVC and Owin, I've installed the NWebSec.MVC and NWebSec.OWIN NuGet packages.

Reading the documentation, many of the options can be set for NWebSec/MVC via the config file, and some of the same options can be set for NWebSec.OWIN in code, via the Startup.cs file.

For example, to add HSTS, I can do the following in 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 the following in startup.cs:

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

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

My question is: do I have to set all the options in both places - or only in one place (in which case, which is better)?

I'd prefer to do all the configuration in the web.config file, but I'm not sure whether this would miss out some things that need to be set in the Startup.cs file.


Solution

  • You can safely set all the configuration in web.config. The OWIN package is there for those that prefer to use the startup class instead of web.config.

    If you should configure e.g. HSTS in both web.config and in middleware, the header would first be set in the response according to web.config. The middleware will run later in the pipeline, and would set the header based on the OWIN configuration without regard to what's in web.config. Consequently, the middleware wins when headers are configured in both places.

    For completeness of this answer: If you use MVC attributes to override the base configuration the OWIN configuration for a particular header will be chosen over web.config when calculating the resulting configuration. So OWIN wins over web.config in all cases.