Retrieve Client IP Address in Azure Container Apps with HTTP Ingress
In article Get IP Address in ASP.NET Core 5, I showed the common approaches to retrieve client IP address in ASP.NET Core applications. That approach will only work if there is no reverse proxy servers involved. This article shows you how to retrieve the IP address for web applications hosted in Azure Container Apps environment.
About reverse proxy
Azure Container Apps uses HTTP edge proxy severs. This means the client IP of HttpContext.Connection.RemoteIpAddress
is the IP address of the proxy servers. If you are not familiar with reverse proxy servers, refer to the following diagram:
Forwarded headers
To get the real client IP address, we need to look into the forwarded HTTP headers. HTTP ingress adds the following headers to pass metadata about the client request to Azure Container Apps:
Header | Description | Values |
---|---|---|
| Protocol used by the client to connect with the Container Apps service. |
|
| The IP address of the client that sent the request. | |
| The host name the client used to connect with the Container Apps service. | |
| The client certificate if | Semicolon seperated list of Hash, Cert, and Chain. For example: |
Hence to get the client IP address, we need to use X-Forwarded-For
header.
The sample code
The following is an enhanced version of getting client IP address in server side applications in ASP.NET Core:
if(!HttpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var ipAddress))
{
ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
}
Other thoughts
If your application is hosted on other cloud like AWS, you need to look after similar headers if the HTTP requests are handled by proxies like AWS API Gateway or Elastic Load Balancer.