Last active
April 27, 2021 18:03
-
-
Save rponte/2166107f65d3f8523e1498ed9b294b82 to your computer and use it in GitHub Desktop.
SpringBoot: how to obtain the user IP address?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.zup.edu.nossocartao.propostas.shared.web; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Component; | |
import org.springframework.web.context.annotation.RequestScope; | |
import javax.servlet.http.HttpServletRequest; | |
import java.util.Objects; | |
import java.util.stream.Stream; | |
@Component | |
@RequestScope | |
public class ClientHostResolver { | |
private final HttpServletRequest request; | |
@Autowired | |
public ClientHostResolver(HttpServletRequest request) { | |
this.request = request; | |
} | |
/** | |
* Resolves client IP address when application is behind a NGINX or other reverse proxy server | |
*/ | |
public String resolve() { | |
String xRealIp = request.getHeader("X-Real-IP"); // used by Nginx | |
String xForwardedFor = request.getHeader("X-Forwarded-For"); // used by the majority of load balancers | |
String remoteAddr = request.getRemoteAddr(); // otherwise uses the remote IP address obtained by our Servlet container | |
// returns the first non null | |
return Stream.of(xRealIp, xForwardedFor, remoteAddr) | |
.filter(Objects::nonNull) | |
.findFirst().orElse(null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Important note: the
X-Forwarded-For
header may return a list of IP adresses, for example: