diff --git a/pom.xml b/pom.xml index 19eb3e62..1aca0b43 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ com.uid2 uid2-shared - 11.4.4 + 11.4.5-alpha-341-SNAPSHOT ${project.groupId}:${project.artifactId} Library for all the shared uid2 operations https://github.com/IABTechLab/uid2docs diff --git a/src/main/java/com/uid2/shared/vertx/RequestCapturingHandler.java b/src/main/java/com/uid2/shared/vertx/RequestCapturingHandler.java index c31d7276..bb9e3de0 100644 --- a/src/main/java/com/uid2/shared/vertx/RequestCapturingHandler.java +++ b/src/main/java/com/uid2/shared/vertx/RequestCapturingHandler.java @@ -62,12 +62,14 @@ public void handle(RoutingContext context) { } long timestamp = System.currentTimeMillis(); - String remoteClient = null; - try { - SocketAddress remoteAddress = context.request().remoteAddress(); - remoteClient = getClientAddress(remoteAddress); - } catch (NullPointerException ex) { - LOGGER.warn("remoteAddress() throws NullPointerException"); + String remoteClient = getClientAddressFromHeaders(context.request()); + if (remoteClient == null) { + try { + SocketAddress remoteAddress = context.request().remoteAddress(); + remoteClient = remoteAddress != null ? remoteAddress.host() : null; + } catch (NullPointerException ex) { + LOGGER.warn("remoteAddress() throws NullPointerException"); + } } HttpMethod method = context.request().method(); @@ -78,11 +80,33 @@ public void handle(RoutingContext context) { context.next(); } - private String getClientAddress(SocketAddress inetSocketAddress) { - if (inetSocketAddress == null) { + private static String getClientAddressFromHeaders(HttpServerRequest request) { + if (request == null || request.headers() == null) { return null; } - return inetSocketAddress.host(); + MultiMap headers = request.headers(); + String value = headers.get("X-Forwarded-For"); + if (value != null && !value.isEmpty()) { + // Leftmost is the original client (RFC 7239) + int comma = value.indexOf(','); + String client = comma >= 0 ? value.substring(0, comma).trim() : value.trim(); + if (!client.isEmpty()) { + return client; + } + } + value = headers.get("X-Real-IP"); + if (value != null && !value.trim().isEmpty()) { + return value.trim(); + } + value = headers.get("True-Client-IP"); + if (value != null && !value.trim().isEmpty()) { + return value.trim(); + } + value = headers.get("CF-Connecting-IP"); + if (value != null && !value.trim().isEmpty()) { + return value.trim(); + } + return null; } private void captureNoThrow(RoutingContext context, long timestamp, String remoteClient, HttpVersion version, HttpMethod method, String uri) {