extractClientIP

Signature

def extractClientIP: Directive1[RemoteAddress]

Description

Provides the value of X-Forwarded-For, Remote-Address, or X-Real-IP headers as an instance of RemoteAddress. When the value is an invalid IP address in the header first seen, then this extractor will return RemoteAddress.Unknown.

The akka-http server engine adds the Remote-Address header to every request automatically if the respective setting akka.http.server.remote-address-header is set to on. Per default it is set to off.

Warning

Clients can send any values in these headers. If the client is not a trusted upstream, the IP address can be malicious and by pass your security rules.

Example

Scala
val route = extractClientIP { ip =>
  complete("Client's ip is " + ip.toOption.map(_.getHostAddress).getOrElse("unknown"))
}

// tests:
Get("/").withHeaders(`Remote-Address`(RemoteAddress(InetAddress.getByName("192.168.3.12")))) ~> route ~> check {
  responseAs[String] shouldEqual "Client's ip is 192.168.3.12"
}
Java
final Route route = extractClientIP(remoteAddr ->
  complete("Client's IP is " + remoteAddr.getAddress().map(InetAddress::getHostAddress)
    .orElseGet(() -> "unknown"))
);

// tests:
final String ip = "192.168.1.2";
final akka.http.javadsl.model.RemoteAddress remoteAddress = 
  akka.http.javadsl.model.RemoteAddress.create(InetAddress.getByName(ip));

final HttpRequest request = HttpRequest.GET("/")
  .addHeader(RemoteAddress.create(remoteAddress)); // 

testRoute(route).run(request)
  .assertEntity("Client's IP is " + ip);

testRoute(route).run(HttpRequest.GET("/"))
  .assertEntity("Client's IP is unknown");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.