Saturday, March 16, 2019

Remove Server Headers in Azure App Service for ASP.NET Core

I'm late to the game, mostly because I haven't been working on web apps for quite some time, but I recently wanted to do some basic security functions on a .NET Core 2.2 application being deployed to an Azure App Service, namely removing headers that identify the platform being used. I have a pretty standard way that I'd done this previously for ASP.NET MVC, but those methods don't work in .NET Core. After doing some digging around, I found that I needed to add a skeleton web.config to configure the web server in the Azure app.

In the configuration included below, you'll see that I'm using the HttpProtocol element to remove the X-Powered-By header. To remove the Server header, I'm using the request filtering feature of IIS 10.0 that has been added to the Azure App Service web server.

 <?xml version="1.0" encoding="utf-8"?>  
 <configuration>  
  <system.webServer>  
   <handlers>  
    <remove name="aspNetCore" />  
    <add name="aspNetCore"   
       path="*"   
       verb="*"   
       modules="AspNetCoreModuleV2"   
       resourceType="Unspecified" />  
   </handlers>  
   <aspNetCore processPath="%LAUNCHER_PATH%"   
         arguments="%LAUNCHER_ARGS%"   
         stdoutLogEnabled="false"   
         stdoutLogFile=".\logs\stdout"   
         hostingModel="InProcess">  
   </aspNetCore>  
   <httpProtocol>  
    <customHeaders>  
     <remove name="X-Powered-By" />  
    </customHeaders>  
   </httpProtocol>  
   <security>  
    <requestFiltering removeServerHeader="true" />  
   </security>  
  </system.webServer>  
 </configuration>  

NOTE: I'm not using Kestrel for this service; it's being hosted by IIS. If you are using Kestrel, you can use middleware to remove the Server header.

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