Explain Codes LogoExplain Codes Logo

How to extract IP Address in Spring MVC Controller get call?

java
prompt-engineering
best-practices
security
Anton ShumikhinbyAnton ShumikhinยทNov 17, 2024
โšกTLDR

Grab the client's IP address in a Spring MVC controller with the HttpServletRequest's getRemoteAddr() method:

// A simple Controller with a 'GET' endpoint @GetMapping("/ip") public String getClientIP(HttpServletRequest request) { // The magic happens here! ๐ŸŽฉ return request.getRemoteAddr(); }

Proxy-handled requests? Extract IP address from the X-Forwarded-For header like a pro ๐Ÿง:

String clientIP = Optional.ofNullable(request.getHeader("X-Forwarded-For")) .orElse(request.getRemoteAddr());

Remember, for accurate IP retrieval in a proxy or load balancer scenario, your server should be forwarding the true headers!

IP address decoding: Behind the Proxies

When your Spring Boot baby ๐Ÿ‘ถ is behind the protective arms of proxies or load balancers, getRemoteAddr() returns the IP address of the last party who sent the request, usually your proxy. Here's what to do:

@GetMapping("/real-ip") public String getRealIP(HttpServletRequest request) { // Dig out some deeper info from the request String forwardedHeader = request.getHeader("X-FORWARDED-FOR"); if (forwardedHeader != null) { // Parse and grab the first IP address if there are multiple return forwardedHeader.split(",")[0]; } // Fall back to the standard way ๐ŸŽถ if no forward headers are found. return request.getRemoteAddr(); }

Safety measures: Protecting against IP spoofing

Trust, but verify! IP spoofing is no laughing matter ๐Ÿ˜ค. Validate and sanitize the IP addresses from headers and getRemoteAddr():

private String validateIP(String ip) { // Place your own validation logic here, a good ol' regex can do the trick ๐Ÿ˜‰ return ip; }

The Batman utils: For when you don't have access to HttpServletRequest

Sometimes HttpServletRequest isn't within reach. Spring comes to the rescue with RequestContextHolder:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest(); // Tada ๐Ÿช„! We got our request object, now we can grab the IP like we did before. String clientIP = request.getRemoteAddr();

X-Real-IP is another worthy contender when you are dealing with Nginx or other reverse proxy software:

String realIp = request.getHeader("X-Real-IP"); if (realIp != null) { // This is as real as it gets, folks ๐Ÿป return realIp; }

Nginx and secure headers: An overview

If Nginx acts as your reverse proxy, it's necessary to pass the X-Real-IP and X-Forwarded-For headers:

location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://localhost:8080; }

Additionally, apply Content-Security-Policy header including default-src 'self' to mitigate risks of injection attacks, indirectly aiding in securing client IP address handling.