How can you get a user's IP in PlayFramework2 ?

前端 未结 2 1620
盖世英雄少女心
盖世英雄少女心 2021-01-13 22:57

For security reasons, sometimes it is needed to block users by IP. In my case, I would like to manage the IP blacklist in a (SQL) database. I guess I can handle the filter p

相关标签:
2条回答
  • 2021-01-13 23:42

    It's now possible with Play 2.0.2+ : RequestHeader.remoteAddress()

    Java :

    String ip = request().remoteAddress();
    

    Scala :

    Action { request =>
        val ip = request.remoteAddress()
    }
    
    0 讨论(0)
  • 2021-01-13 23:46

    If your Play! app is behind nginx (or any other reverse proxy), request.remoteAddress() will only return the IP address of your nginx host. In order to retrieve the real IP of the client you should have the following in your proxy_pass configuration of nginx:

    location / {
      proxy_pass        http://play-app:9000;
      proxy_set_header  X-Real-IP  $remote_addr;
    }
    

    This will add the client IP as parameter to the header

    doc: Nginx

    And then within your Play! app you would retrieve it like this:

    request.headers.get("X-Real-IP") //In Java
    request.headers.get("X-Real-IP") //In Scala
    

    doc: Java, Scala

    0 讨论(0)
提交回复
热议问题