2017-08-07 71 views
0

此刻我正在使用NWebsec.AspNetCore.Middleware nuget包来实现CSP头。当简单地创建一个新的ASP.NET Core 1.1 MVC应用程序并按照后续步骤修改启动时,仍然可以通过控制台注入脚本。我错过了什么?ASP.Net Core 1.1 - Angular2项目CSP不工作

public class Startup 
{ 
    public Startup(IHostingEnvironment env) 
    { 
     var builder = new ConfigurationBuilder() 
      .SetBasePath(env.ContentRootPath) 
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
      .AddEnvironmentVariables(); 
     Configuration = builder.Build(); 
    } 

    public IConfigurationRoot Configuration { get; } 

    // This method gets called by the runtime. Use this method to add services to the container. 
    public void ConfigureServices(IServiceCollection services) 
    { 
     // Add framework services. 
     services.AddMvc(); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
      app.UseBrowserLink(); 
     } 
     else 
     { 
      app.UseExceptionHandler("/Home/Error"); 
     } 

     app.UseStaticFiles(); 

     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}"); 
     }); 

     app.UseCsp(csp => 
     { 
      csp.DefaultSources(src => src.Self()); 
     }); 
    } 
} 

内容是将CSP安全设置为Angular2生成的静态文件(WebPack)。但是CSP似乎不适用。

回答

1

中间件从上到下运行,这意味着如果中间件提前退出,那么稍后在管道中注册的中间件将不会运行。

例如,您通常在MVC中间件之前配置静态文件中间件。这样,应用程序将第一个试图找到一个匹配当前请求并直接服务的静态文件(它将跳过MVC)。只有当没有文件时,它才会回退到MVC路径查找。

这最终意味着为了保护东西,或者将用户锁定在“完成”真正的中间件(那些实际返回的东西)之外的任何东西都必须在流水线开始时注册。

在你的情况,你需要确保你打电话UseCsp()之前UseMvc以确保在CSP中间件的MVC中间件之前运行。