Azure function client ip

Casper Rubæk 246 Reputation points
2022-06-22T21:45:26.47+00:00

I pass traffic through API Management to c# Function App. How can I get the client IP?

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,782 questions
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,327 questions
0 comments No comments
{count} votes

Accepted answer
  1. Mike Urnun 9,761 Reputation points Microsoft Employee
    2022-06-23T20:09:01.793+00:00

    Hello @Casper Rubæk - Thanks for confirming in the private comments. Posting the below as a resolution to this thread:

    Since APIM is in front of the Function App, and given how APIM maintains Client IP through context variable as follows: context.Request.IpAddress

    The Client IP needs to be passed along to the Function App by way of defining a header via a small policy snippet:

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

    The corresponding value then can be accessed in your HttpTrigger function via HttpRequest object as follows:

    #r "Newtonsoft.Json"  
      
    using System.Net;  
    using Microsoft.AspNetCore.Mvc;  
    using Microsoft.Extensions.Primitives;  
    using Newtonsoft.Json;  
      
    public static async Task<IActionResult> Run(HttpRequest req, ILogger log)  
    {  
       ....  
      
       var clientIP = req.Headers["X-Forwarded-Client-Ip"];  
       ....  
    }  
    

    -------------------------------------------------------------------------------

    Please consider contributing to MS Q&A by marking 'Accepted Answer' and ‘Upvoting’ as applicable.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. MughundhanRaveendran-MSFT 12,436 Reputation points
    2022-06-23T05:21:08.81+00:00

    Hi @Casper Rubæk ,

    Thanks for reaching out to Q&A forum.

    In the function app, the list of client ip that is getting blocked due to ip restriction is available in the "Diagnose and solve problems" blade in portal. However, if you are looking to get all the client ips that are sending requests to the function app, then you will have to write your own logic/code to get the client ip.
    Please refer to this article to get the client ip using C# : Get client ip using C#

    Application insights temporarily collect the client ip addresses you can also explore it: https://learn.microsoft.com/en-us/azure/azure-monitor/app/ip-collection?tabs=net#default-behavior

    I hope this helps! Feel free to reach out to me if you have any further queries or concerns.

    Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community looking for help on similar topics.