将安全标头添加到ASP.NET Core 3.1 Web Api

问题描述

我需要在我的新ASP.NET Core 3.1 Web API中添加一些安全标头。在MVC和Webform中,我曾经使用过以下web.config文件中的代码

poverty

我知道我们也可以在.NET Core中有一个web.config文件,但是我想通过在启动类中添加自定义代码来实现。我发现很少有文章使用某些NUGET软件包,但是如果有人可以给我一个清晰的画面来在.Net Core中添加安全标头,那就太棒了。 预先感谢。

解决方法

在您的代码中创建一个中间件类CustomResponseHeaderMiddleware

public class CustomResponseHeaderMiddleware
{
    private readonly RequestDelegate _next;

    public CustomResponseHeaderMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        //To add Headers AFTER everything you need to do this
        context.Response.OnStarting(state =>
        {
            var httpContext = (HttpContext)state;
            httpContext.Response.Headers.Add("Strict-Transport-Security","max-age=31536000");
            httpContext.Response.Headers.Add("X-Content-Type-Options","nosniff");
            httpContext.Response.Headers.Add("X-Xss-Protection","1; mode=block");
            httpContext.Response.Headers.Add("X-Frame-Options","SAMEORIGIN");
            //... and so on
            return Task.CompletedTask;
        },context);

        await _next(context);
    }
}

并将此中间件注册到startup.cs文件中

public void Configure(IApplicationBuilder app,IHostingEnvironment env)
{
    // ....
    app.UseMiddleware(typeof(CustomResponseHeaderMiddleware));
    
    app.UseMvc();
}
,

您可以使用NWebsec软件包来添加这样的安全策略。

app.UseCsp(options =>
{
    options.BlockAllMixedContent()
    .ScriptSources(s => s.Self())
    .StyleSources(s => s.Self())
    .StyleSources(s => s.UnsafeInline())
    .FontSources(s => s.Self())
    .FormActions(s => s.Self())
    .FrameAncestors(s => s.Self())
    .ImageSources(s => s.Self());
});
app.UseXfo(option =>
{
    option.Deny();
});
app.UseXXssProtection(option =>
{
    option.EnabledWithBlockMode();
});
app.UseXContentTypeOptions();
app.UseReferrerPolicy(opts => opts.NoReferrer());

删除服务器标头

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseKestrel(options =>
        {
            options.AddServerHeader = false;
        })
        .UseStartup<Startup>();

<configuration> 
  <system.webServer>
    <security>
      <requestFiltering removeServerHeader="true" />
    </security>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

添加HSTS

app.UseHsts(options =>
{
    options.MaxAge(days: 365).IncludeSubdomains().Preload();
});

添加Feature-Policy

app.Use(async (context,next) =>
{
    if (context.Response.Headers.All(x => x.Key != "Feature-Policy"))
        context.Response.Headers.Add("Feature-Policy",new[] { "accelerometer 'none'; camera 'none'; geolocation 'self'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; payment 'none'; usb 'none'" });

    await next();
});