Raymond Raymond

Retrieve Client IP Address in Azure Container Apps with HTTP Ingress

event 2023-06-24 visibility 900 comment 0 insights toc
more_vert
insights Stats
toc Table of contents
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:

Forward Proxy and Reverse Proxy


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

X-Forwarded-Proto

Protocol used by the client to connect with the Container Apps service.

http or https

X-Forwarded-For

The IP address of the client that sent the request.


X-Forwarded-Host

The host name the client used to connect with the Container Apps service.


X-Forwarded-Client-Cert

The client certificate if clientCertificateMode is set.

Semicolon seperated list of Hash, Cert, and Chain. For example: Hash=....;Cert="...";Chain="...";

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.


References

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts