How to extract IP Address in Spring MVC Controller get call?
Grab the client's IP address in a Spring MVC controller with the HttpServletRequest
's getRemoteAddr()
method:
Proxy-handled requests? Extract IP address from the X-Forwarded-For
header like a pro ๐ง:
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:
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()
:
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
:
X-Real-IP
is another worthy contender when you are dealing with Nginx or other reverse proxy software:
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:
Additionally, apply Content-Security-Policy
header including default-src 'self'
to mitigate risks of injection attacks, indirectly aiding in securing client IP address handling.
Was this article helpful?