title: Prevent altering X-Forwarded-For
body: <p>We have a simple api that is hosted in azure vm, we have included an application gateway. And the application works fine, until we require to log the clients ip because we have to determine the location of our clients via ipstack.</p>
  
  <p>I have added this code in our HomeController</p>
  
  <pre><code>var ip = string.Empty;
  
  if (HttpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
  {
      ip = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
  }
  </code></pre>
  
  <p>This works fine, until I decided to use Postman to call the api and added the X-Forwarded-For in the request.</p>
  
  <p><a href="https://i.stack.imgur.com/LfqC5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LfqC5.png" alt="postman"></a>
  <a href="https://i.stack.imgur.com/9WkBK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9WkBK.png" alt="fake ip injected"></a></p>
  
  <p>I have included the header as a result in our api just to check and...</p>
  
  <pre><code>"X-Forwarded-For": "&lt;script&gt;alert('test');&lt;/script&gt;,192.168.0.1", //masked my real Ip
  
  "X-Forwarded-For": "0.0.0.0,192.168.0.1" //fake ip (0.0.0.0)
  </code></pre>
  
  <p>Is there anyway to prevent this?</p>
  
  <p>I have included the below code in startup.cs but still no luck. </p>
  
  <pre><code>            services.Configure&lt;ForwardedHeadersOptions&gt;(c =&gt;
              {
                  //c.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                  //c.ForwardLimit = 1;
                  //c.KnownProxies.Add(IPAddress.Parse("127.0.0.0"));
                  c.ForwardedForHeaderName = "X-Forwarded-For-My-Custom-Header-Name";
              });
  </code></pre>