2017-08-25 9 views
2

X駆動バイヘッダ.NETコアに取り除く方法:私はこのミドルウェア使用しようとした2.0

public class SecurityHeadersMiddleware 
{ 
    private readonly RequestDelegate next; 

    public SecurityHeadersMiddleware(RequestDelegate next) 
    { 
     this.next = next; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     context.Response.OnStarting(state => 
     { 
      var ctx = (HttpContext)state; 

      if (!ctx.Response.Headers.ContainsKey("Arr-Disable-Session-Affinity")) 
      { 
       ctx.Response.Headers.Add("Arr-Disable-Session-Affinity", "True"); // Disables the Azure ARRAffinity cookie 
      } 

      if (ctx.Response.Headers.ContainsKey("Server")) 
      { 
       ctx.Response.Headers.Remove("Server"); // For security reasons 
      } 

      if (ctx.Response.Headers.ContainsKey("x-powered-by") || ctx.Response.Headers.ContainsKey("X-Powered-By")) 
      { 
       ctx.Response.Headers.Remove("x-powered-by"); 
       ctx.Response.Headers.Remove("X-Powered-By"); 
      } 

      if (!ctx.Response.Headers.ContainsKey("X-Frame-Options")) 
      { 
       ctx.Response.Headers.Add("X-Frame-Options", "DENY"); 
      } 

      return Task.FromResult(0); 
     }, context); 

     await next(context); 
    } 
} 

Xが搭載バイ 応答ヘッダーに依然として存在するasp.net

+0

あなたが私の答えが役に立っていると感じたら/助けにしてください。それを他の人々が恩恵を受けることができるように答えとしてマークしてください。 –

答えて

6
言います

私が知る限り、これらのヘッダーの削除は、IISの一部であるリクエストフィルタリングモジュールを使用して容易になります。ヘッダを削除するには

は、次の内容で、あなたのサイトに保存されているweb.configファイルを持っている必要があります:

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 

    <!-- To customize the asp.net core module uncomment and edit the following section. 
    For more info see https://go.microsoft.com/fwlink/?linkid=838655 --> 

    <system.webServer> 
    <handlers> 
     <remove name="aspNetCore"/> 
     <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/> 
    </handlers> 
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" /> 
    <httpProtocol> 
     <customHeaders> 
     <remove name="X-Powered-By" /> 
     </customHeaders> 
    </httpProtocol> 
    </system.webServer> 


</configuration> 

は、あなたのネットコアアプリケーションのルートフォルダに、このweb.configファイルを追加します。

次に、x-powered-byヘッダーが削除されます。このような

結果:

enter image description here

+0

はい、ヘッダーがIISによって生成されるので、これがこれを行う唯一の方法であるようです。 .Net Core Hostingチームのコメントなど、いくつか詳しい情報があります:https://github.com/aspnet/Hosting/issues/571 – TallMcPaul

4
  • を削除するには:あなたは、そのヘッダを削除するKestralを指示する必要がありレスポンスヘッダから "サーバーケストレルを"

-.NETコア1

var host = new WebHostBuilder() 
     .UseKestrel(c => c.AddServerHeader = false) 
     .UseContentRoot(Directory.GetCurrentDirectory()) 
     .UseIISIntegration() 
     .UseStartup<Startup>() 
     .Build(); 

-NETコア2

WebHost.CreateDefaultBuilder(args) 
       .UseKestrel(c => c.AddServerHeader = false) 
       .UseStartup<Startup>() 
       .Build(); 
関連する問題