簡體   English   中英

將安全標頭添加到 ASP.NET 核心 3.1 Web Api

[英]Adding Security Headers to ASP.NET Core 3.1 Web Api

我需要在我的新 ASP.NET Core 3.1 Web API 中添加一些安全標頭。 在 MVC 和 webform 中,我曾經在 web.config 文件中使用以下代碼:

<httpProtocol>
      <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=31536000"/>
        <add name="X-Content-Type-Options" value="nosniff"/>
        <add name="X-Xss-Protection" value="1; mode=block"/>
        <add name="X-Frame-Options" value="SAMEORIGIN"/>
        <add name="Content-Security-Policy" value="default-src https:; img-src * 'self' data: https:; style-src 'self' 'unsafe-inline' www.google.com platform.twitter.com cdn.syndication.twimg.com fonts.googleapis.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' www.google.com cse.google.com cdn.syndication.twimg.com platform.twitter.com platform.instagram.com www.instagram.com cdn1.developermedia.com cdn2.developermedia.com apis.google.com www.googletagservices.com adservice.google.com securepubads.g.doubleclick.net ajax.aspnetcdn.com ssl.google-analytics.com az416426.vo.msecnd.net/;"/>
        <add name="Referrer-Policy" value="no-referrer-when-downgrade"/>
        <add name="Feature-Policy" value="geolocation 'none';midi 'none';notifications 'none';push 'none';sync-xhr 'none';microphone 'none';camera 'none';magnetometer 'none';gyroscope 'none';speaker 'self';vibrate 'none';fullscreen 'self';payment 'none';"/>
        <remove name="X-Powered-By" />
        <remove name="X-AspNet-Version" />
        <remove name="Server" />
      </customHeaders>
</httpProtocol>

我知道我們也可以在 .NET Core 中有一個 web.config 文件,但我想通過在啟動 class 中添加自定義代碼來實現這一點。 我發現很少有文章使用一些 NUGET 包,但如果有人能給我一個清晰的圖片來在.Net Core 中添加安全標頭,那就太棒了。 提前致謝。

在您的代碼中創建一個中間件 class 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 package 添加這樣的安全策略。

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());

刪除服務器 header

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();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM