Подтвердить что ты не робот

Как удалить заголовок x-powered-by в .net core 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-powered-by все еще присутствует в заголовке ответа, в котором говорится asp.net

4b9b3361

Ответ 1

  • В дополнение к ответу @Brando Zhang, чтобы удалить "Server: Kestrel" из заголовка ответа, необходимо указать Kestral удалить его заголовок

.NET Core 1

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

-NET Core 2

WebHost.CreateDefaultBuilder(args)
               .UseKestrel(c => c.AddServerHeader = false)
               .UseStartup<Startup>()
               .Build();

Ответ 2

Насколько мне известно, удаление этих заголовков облегчается модулем фильтрации запросов, который является частью 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.

Результат выглядит следующим образом:

введите описание изображения здесь

Ответ 3

В качестве альтернативы ответам выше вы можете использовать преобразование конфигурации. Таким образом, web.config будет по-прежнему генерироваться через SDK издателя dotnet, но его можно смешивать с конкретными тегами, такими как удаление заголовка.

В корне проекта создайте новый файл web.Release.config следующим образом:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <location>

    <!-- 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>
      <httpProtocol xdt:Transform="InsertIfMissing">
        <customHeaders>
          <remove name="X-Powered-By" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>

  </location>
</configuration>

Обратите внимание, что это файл преобразования, а не фактический файл web.config.