How do I extract an ip address in the azure api management policy?
Asked Answered
Z

2

6
  1. Is there an out of the box policy to extract the incoming ip address? I could not find one.
  2. Do I need to write code to do that? If so, how do I go about it? What are the other alternatives?
Zimmermann answered 10/7, 2016 at 3:45 Comment(0)
C
5

You can extract IP address in any policies using policy expressions. The expression would be context.Request.IpAddress

Commodity answered 11/7, 2016 at 16:53 Comment(0)
A
2

You can definitely use policy expressions.

But an easier approach might be the below:

If your goal is to capture the origin IP address (and not Azure's) on your backend (for logging purposes, etc.), then:

Whenever Azure API Management Studio forwards requests to your backend, it includes the header X-Forwarded-For

E.g. {[X-Forwarded-For, 123.45.67.891, 13.75.131.25:1795]}

The first IP Address is the one you want. The second IP Address is actually Azure's.

E.g. First, A mobile app makes a request to Azure API Mgmt --> Second, Azure API Mgmt forwards the request to your back end --> Lastly, you capture client's the IP (i.e. the mobile device's IP) from X-Forwarded-For.

How you capture the IP from the headers on your backend is up to you and what technology you're using (e.g. ASP.net core, node.js, etc.).

Here's a snippet of code where I'm capturing the IP

private LogMetadata BuildRequestMetadata(HttpRequestMessage request, Task<string> requestBody)
{    
    var headers = request.Headers.ToDictionary(d => d.Key, d => d.Value.Join(", "));

    // If header X-Forwarded-For is included, 
    // it means the request is coming from Azure API MGMT studio. 
    // Example header value: {[X-Forwarded-For, 123.45.67.891 (Mobile Device), 13.75.131.25:1795 (Azure API Mgmt)]}
    var clientIp = 
        headers.ContainsKey("X-Forwarded-For") 
            ? headers["X-Forwarded-For"].Split(',')[0] 
            : request.GetOwinContext().Request.RemoteIpAddress;  
}
Anthracene answered 4/7, 2018 at 1:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.