Azure Functions: getting the client IP address

When using Azure Functions, sometimes is required to log the IP address of the client calling your function app. Unfortunately, there’s not an out of the box way of doing that and sometimes I’ve found it quite tricky (just today I had this requirement on a customer site and they was not able to do that, so here is the reason of this post).

To retrieve the client IP address of your Azure Function, you need to inspect the HTTP request and check for the XForwarded-For request header. The X-Forwarded-For request header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through a proxy server.

The XForwarded-For request header is automatically added on every call from the platform and helps you identify the IP address of a client calling your function app. Please remember that this value is added to the request header ONLY if the function app is deployed on Azure (it doesn’t work if you test it locally).

To give an example, here is a simple HttpTrigger Azure Function (standard skeleton of a consumption app) where I’ve added the client IP retrieval code. The code is handled in the GetIpFromRequestHeaders function:

If you call this function, the HTTP request is inspected and if the XForwarded-For request header is found, the IP address is returned as a response:

Things are different if your Azure Function app is under Azure API Management. In this case, Azure API Management maintains Client IP through a context variable called context.Request.IpAddress.

To retrieve the Client IP, it needs to be passed along to the Function App by defining a header via the following policy snippet:

<set-header name="X-Forwarded-Client-Ip" exists-action="override">
  <value>@(context.Request.IpAddress)</. value>

and then the corresponding value can be accessed in your Azure Function code like in the following snippet:

var clientIP = req.Headers["X-Forwarded-Client-Ip"];

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.