【问题标题】:ASP.Net Core 1.1 - Angular2 project CSP not workingASP.Net Core 1.1 - Angular2 项目 CSP 不工作
【发布时间】:2017-09-05 05:45:41
【问题描述】:

目前我正在使用 NWebsec.AspNetCore.Middleware nuget 包来实现 CSP 标头。当简单地创建一个新的 ASP.NET Core 1.1 MVC 应用程序并如下修改启动时,仍然可以通过控制台注入脚本。我错过了什么?

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。

【问题讨论】:

    标签: c# angular content-security-policy asp.net-core-1.1


    【解决方案1】:

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

    例如,您通常在 MVC 中间件之前配置静态文件中间件。这样,应用程序将首先尝试查找与当前请求匹配的静态文件并直接提供该文件(这将跳过 MVC)。只有在没有文件的情况下才会回退到MVC路由查找。

    这最终意味着所有用于保护内容或阻止用户使用“真实”中间件(实际返回内容的中间件)完成请求的所有内容都必须在管道开始时进行注册。

    在您的情况下,您需要确保调用 UseCsp() 之前 UseMvc 以确保 CSP 中间件在 MVC 中间件之前运行。

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 2017-04-04
      • 2017-11-01
      相关资源
      最近更新 更多