extractDirectClientIP
Description
Provides the value of the AttributeKeys.remoteAddressAttributeKeys.remoteAddress attribute, which is the address of the peer of the connection the request arrived on. It requires the pekko.http.server.remote-address-attribute setting to be on and provides RemoteAddress.Unknown otherwise.
Unlike extractClientIP, this directive ignores the X-Forwarded-For and X-Real-IP headers, so the address it provides cannot be chosen by the client. Note that behind a proxy this is the address of the proxy and not of the client that the proxy forwarded the request for.
Example
- Scala
-
source
val route = extractDirectClientIP { ip => complete("Client's ip is " + ip.toOption.map(_.getHostAddress).getOrElse("unknown")) } // tests: val remoteAddress = RemoteAddress(InetAddress.getByName("192.168.3.12")) Get("/").withAttributes(Map(AttributeKeys.remoteAddress -> remoteAddress)) ~> route ~> check { responseAs[String] shouldEqual "Client's ip is 192.168.3.12" } // a client cannot choose the address by sending a header Get("/").withHeaders(`X-Forwarded-For`(RemoteAddress(InetAddress.getByName("1.2.3.4")))) ~> route ~> check { responseAs[String] shouldEqual "Client's ip is unknown" } - Java
-
source
final Route route = extractDirectClientIP( remoteAddr -> complete( "Client's IP is " + remoteAddr .getAddress() .map(InetAddress::getHostAddress) .orElseGet(() -> "unknown"))); // tests: final String ip = "192.168.1.2"; final org.apache.pekko.http.javadsl.model.RemoteAddress remoteAddress = org.apache.pekko.http.javadsl.model.RemoteAddress.create(InetAddress.getByName(ip)); testRoute(route) .run(HttpRequest.GET("/").addAttribute(AttributeKeys.remoteAddress, remoteAddress)) .assertEntity("Client's IP is " + ip); // a client cannot choose the address by sending a header testRoute(route) .run(HttpRequest.GET("/").addHeader(XForwardedFor.create(remoteAddress))) .assertEntity("Client's IP is unknown");
2.0.0-M2