Skip to content

Getting the Client IP from X-Forwarded-For: Building a Trusted Value Behind Reverse Proxies

Interactive Diagram

새 탭 ↗

Access logs, rate limits, geo-blocking, and administrative IP allowlists all depend on one question: who sent this request? Yet an application behind a reverse proxy cannot observe that value itself. It sees the socket address of the last hop, while the original client address is only a claim written into a header by some upstream proxy.

This article has a single conclusion. Code that reads the leftmost X-Forwarded-For value is an authorization vulnerability unless a trust boundary already exists. Trust is not created by the header itself, nor by a vendor’s brand. It is created by a network topology in which backends cannot be reached directly, plus a first proxy that overwrites or normalizes client-supplied forwarding headers.

Before forwarded processing, getRemoteAddr() returns the transport peer

Section titled “Before forwarded processing, getRemoteAddr() returns the transport peer”

In the servlet specification, ServletRequest.getRemoteAddr() returns the IP address of the client “or last proxy” that sent the request. In other words it is the transport peer on the other end of the TCP connection. This describes the connection counterpart observed by the container before forwarded-header processing. It need not be the end user; after a NATIVE valve or FRAMEWORK filter, the same accessor can return a header-derived logical client address.

  • If a client connects directly to the application, getRemoteAddr() returns the real user address.
  • With client → proxyA → proxyB → application, it returns proxyB’s address.
  • With a service mesh sidecar or ingress controller in front, it may return a loopback or Pod address.
  • The value may be an IPv4 dotted quad or an IPv6 form such as 2001:db8::1. An IPv6 string contains several colons, so code that “strips the port by splitting on a colon” destroys IPv6 addresses.

The trust anchor is the raw transport peer before forwarded processing. Do not reuse the processed getRemoteAddr() as evidence of that raw peer; distinguish original connection logs from the processed value.

MDN describes X-Forwarded-For (XFF) as a de-facto standard header for identifying the originating IP address of a client connecting through a proxy. Its standardized counterpart is RFC 7239’s Forwarded, which is used far less often.

The rule is simple appending. Each proxy adds the peer address it observed to the end of the existing value. With client 192.0.2.10, proxyA 198.51.100.20, and proxyB 198.51.100.30, the header grows like this.

GET /orders HTTP/1.1
Host: api.example.com
# as proxyA forwards toward the application
X-Forwarded-For: 192.0.2.10
# as proxyB forwards toward the application
X-Forwarded-For: 192.0.2.10, 198.51.100.20

Before forwarded processing, the application’s getRemoteAddr() returns 198.51.100.30, and the leftmost header entry is 192.0.2.10. A common misreading starts here. “Leftmost equals the real client” is a postcondition that holds only if every hop appended honestly; it is not a property the protocol guarantees.

Reading the leftmost value is an authorization vulnerability

Section titled “Reading the leftmost value is an authorization vulnerability”

XFF is just a request header. A client can send whatever it likes from the very first hop. If the client sends X-Forwarded-For: 203.0.113.9, proxyA dutifully appends the peer it observed.

PlantUML Diagram

From the application’s viewpoint the spoofed prefix and an honest prefix are indistinguishable. Both are just IP strings at the left of a list, and the header carries no information about which entry came from an actual observation. The ForwardedHeaderFilter documentation states the same point: an application cannot know whether forwarded headers were added by a trusted proxy or by a malicious client, and it is imperative that a proxy at the edge of trust be configured to drop forwarded headers arriving from outside.

Parsing alone cannot manufacture trust. However, the fixed trusted-proxy-count approach described by MDN is valid when the hop count is exact on every path and bypasses are blocked. Prepending fake entries alone does not shift a correctly chosen right-relative position. Shorter bypass paths, changing hop counts, and incorrect trusted lists are the risks. Walking from the right past trusted proxy addresses to the first untrusted address is another valid design; this article chooses edge overwrite below.

Trust comes from topology plus first-hop overwrite

Section titled “Trust comes from topology plus first-hop overwrite”

The edge-overwrite design chosen here requires two conditions together.

  1. Network topology: the backend accepts traffic only from designated proxies. Private subnets, security groups, a NetworkPolicy, or mTLS all serve the same goal: a client must not be able to open a TCP connection to the application while bypassing the proxy.
  2. First-hop overwrite: the frontmost proxy at the trust boundary ignores forwarding headers arriving from outside and rewrites them with the peer address it observed. Only internal hops are allowed to append.
PlantUML Diagram

The decisive element in this diagram is not the header but the fact that A discarded it. Everything to the left afterwards is a record of an observation rather than a string.

The claim that a managed load balancer makes you safe automatically is false. Read vendor documentation literally.

BehaviourWhat the documentation actually saysDesign consequence
ALB default XFF handlingCreates the header from the client IP when absent, otherwise appends to itThe default is not overwrite; preserve/modify/remove must be chosen explicitly
Application Gateway request modificationInserts several forwarding headers, with x-forwarded-for formatted as a comma-separated list of IP:portPorts arrive attached, so the application must assume normalization is required
Header rewrite capabilityHeader and URL rewriting is available only on specific SKUsOverwrite is a configuration task, not a built-in guarantee
nginx realip moduleAccepts the header value only for requests from addresses listed in set_real_ip_fromThe trusted list is the policy; a wide list removes the protection

The test is therefore never “is it managed?” but “does this hop discard external headers, and can this hop be bypassed?”

The Forwarded standard versus X-Forwarded-For in practice

Section titled “The Forwarded standard versus X-Forwarded-For in practice”

RFC 7239 defines a standard Forwarded header carrying for, by, proto, and host parameters in a single field, such as Forwarded: for=192.0.2.10;proto=https, for=198.51.100.20. Its grammar includes quoted forms for IPv6 addresses and ports, which leaves less parsing ambiguity.

XFF nevertheless remains dominant for a simple reason. RFC 7239 was standardized in 2014, but XFF and X-Forwarded-Proto were already wired into most proxies, CDNs, load balancers, and frameworks before that, and MDN notes that the standard header is much less frequently used. What matters is declaring the adopted header family and precedence. At the edge, remove both external Forwarded and X-Forwarded-* headers, then generate only the chosen family. The ForwardedHeaderFilter(boolean useStandardHeader) constructor applies only to versions that provide it: the currently linked Spring Framework 7.0.9 API has it, but the compared 6.2.12 source does not. The default constructor retains the historical behavior of checking Forwarded first and X-Forwarded-* next. This article has not verified which constructor Boot auto-registration uses, so do not assume it selects a header family automatically.

The Java discussion below was compared against the Spring Framework 6.2.12 servlet implementation; the Tomcat policy link targets the 10.1 documentation. These are not recorded Spring Boot/Framework/Tomcat deployment versions or execution results. Before applying the examples, verify dependencies, container versions, and Boot auto-registration conditions.

Scattering hand-rolled split(",")[0] code across the codebase is the worst option. Trust policy gets duplicated in every fragment, and IPv6, port, and whitespace handling drift apart. Use the framework’s integration point first.

According to the Spring Boot documentation, server.forward-headers-strategy accepts three values.

  • NATIVE: delegates to the web server’s own forwarded-header support. On Tomcat that means RemoteIpValve, which evaluates the chain from the right according to the connection peer and internalProxies/trustedProxies policy and rewrites what request.getRemoteAddr() returns as a result. The trusted list is the heart of the configuration.
  • FRAMEWORK: registers ForwardedHeaderFilter on the servlet stack and ForwardedHeaderTransformer on the reactive stack. They extract header values and wrap the request and response so they reflect the originating client’s perspective. In removeOnly mode they strip the headers without using them.
  • NONE: does nothing. The property defaults to NATIVE when running on a supported cloud platform, and to NONE everywhere else.

One thing must be stated precisely: this setting does not mean “return the first XFF entry.” NATIVE reconstructs the request using the container’s trusted-proxy policy. The FRAMEWORK filter does not itself validate a peer allowlist, so it relies on upstream topology and overwrite policy. tomcat.remoteip.internal-proxies does not automatically provide peer validation under FRAMEWORK. Enabling the property without first establishing a trust boundary simply makes the application reflect spoofed values faithfully.

NATIVE option (Tomcat):

server:
forward-headers-strategy: native
tomcat:
# When using NATIVE, narrow the trusted proxy range explicitly.
remoteip:
remote-ip-header: x-forwarded-for
protocol-header: x-forwarded-proto
internal-proxies: "198\\.51\\.100\\.(20|30)"

FRAMEWORK option (requires an upstream trust boundary):

server:
forward-headers-strategy: framework

These configurations are alternatives, not one combined configuration. The documentation-reserved addresses must be replaced with the actual deployment’s proxy list.

What you need next is not parsing but a request-scoped context. Controllers, services, and audit logging should observe the same value while only one place knows how to obtain it.

The required order is raw-peer trust decision/upstream blocking → forwarded processing → ClientIpContextFilter → IP-consuming authorization/controllers/services. @Order(Ordered.HIGHEST_PRECEDENCE + 1) states only the context filter’s order. Under FRAMEWORK, ForwardedHeaderFilter must be registered earlier; a NATIVE valve runs before servlet filters. @Component alone does not guarantee this ordering. Verify actual Boot registration and the Spring Security filter chain; no ordering test was run for this example.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class ClientIpContextFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
try {
// Use the value forward-headers-strategy already reconstructed.
// Not re-parsing the header here is the whole point.
ClientIpContext.set(normalizeForDisplay(request.getRemoteAddr()));
chain.doFilter(request, response);
} finally {
ClientIpContext.clear(); // always clean up in finally
}
}
/** Display-only bracket/port cleanup, not IP validation or security canonicalization. */
static String normalizeForDisplay(String raw) {
if (raw == null || raw.isBlank()) {
return "unknown";
}
String value = raw.trim();
if (value.startsWith("[")) { // [2001:db8::1]:51514
int end = value.indexOf(']');
return end > 0 ? value.substring(1, end) : "unknown";
}
long colons = value.chars().filter(c -> c == ':').count();
if (colons == 1) { // 192.0.2.10:51514
return value.substring(0, value.indexOf(':'));
}
return value; // bare IPv6 or IPv4
}
}

normalizeForDisplay only cleans up display notation. It does not validate IP syntax, malformed ports/bracket suffixes, or normalize equivalent IPv6 and IPv4-mapped IPv6 forms. Storing a value in the context does not validate it for authorization. For an IP allowlist, use a validated IP-literal parser without DNS lookup and an address-level comparison/CIDR policy separately; reject unknown, malformed, and unsupported values fail-closed.

public final class ClientIpContext {
private static final ThreadLocal<String> CLIENT_IP =
new NamedThreadLocal<>("clientIp");
private ClientIpContext() {
}
public static void set(String clientIp) {
CLIENT_IP.set(clientIp);
}
/** Returns empty rather than letting callers guess a value. */
public static Optional<String> get() {
return Optional.ofNullable(CLIENT_IP.get());
}
public static void clear() {
CLIENT_IP.remove();
}
}

State the boundaries of ThreadLocal explicitly

Section titled “State the boundaries of ThreadLocal explicitly”

A ThreadLocal context is convenient but safe only under conditions.

  • Always clear it in finally. Servlet containers reuse threads. Without cleanup, the next request can log the previous request’s client IP, a cross-request leak in audit data.
  • It does not cross async or reactive boundaries. @Async, CompletableFuture, a separate executor, and WebFlux operator chains run on different threads, so ClientIpContext.get() will be empty. Use the Reactor Context in WebFlux, and either pass the value as an argument or implement propagation with a TaskDecorator for explicit executors.
  • Watch servlet async dispatch. OncePerRequestFilter does not run again on async dispatch by default, so the context may already be cleared at the point where async work executes.
  • If only a few places need the value, skip the context entirely. Accepting it as a controller parameter and passing it explicitly to services is easier to trace. A context is justified only when the value is needed broadly across the call path, as with audit logging.

A trust boundary depends on deployment shape, so unit tests alone are insufficient. The table below lists expected conditions to verify against the actual deployment, not executed results. Observe raw XFF before the forwarded filter hides it, and check the processed address and context separately.

ScenarioRequest/observation pointRaw XFF before forwarded processingExpected processed getRemoteAddr()/contextBoundary to inspect on failure
Direct-to-backend requestBypass the proxyMust not reach the applicationConnection refused; no contextNetwork topology and bypass paths
Spoofed XFFEdge ingress: 203.0.113.9; client: 192.0.2.10Internal ingress: 192.0.2.10; application ingress: 192.0.2.10, 198.51.100.20Single 192.0.2.10Edge overwrite, conflicting-header removal, processing order
Normal single proxyClient → edge → applicationApplication ingress: 192.0.2.10Single 192.0.2.10Forwarded strategy and trusted-proxy policy
Two chained trusted proxiesClient → edge → internal → applicationInternal ingress: 192.0.2.10; application ingress: 192.0.2.10, 198.51.100.20Single 192.0.2.10, not the whole chainInternal append, peer-trust policy, filter order
IPv6 client2001:db8::1Valid IPv6 notation generated by the proxyAddress meaning 2001:db8::1; check display and authorization validation separatelyIPv6 parser and address comparison policy
Port-bearing notationDeliver 192.0.2.10:51514That notation at application ingressVerify address extraction by a supporting container/framework parser; the display example is 192.0.2.10Supported parser forms; display cleanup is not authorization validation
Malformed/unknownInvalid IP literal or absent valueInspect actual rejection/forwarding behaviorAuthorization denied; a context string alone does not permit accessFail-closed policy and validation parser
Consecutive/concurrent requestsRequests from different clientsSeparate raw XFF for each requestPer-request values, empty context after completionThreadLocal cleanup and filter order

The second row matters most. If the spoofed-XFF test does not pass, no trusted client IP exists even when every other row passes.

The raw transport peer before forwarded processing is not guaranteed to be the end user, while X-Forwarded-For claims the end user but can be forged. Deployment structure, not parsing cleverness, closes that gap. Hide the backend behind proxies, make the frontmost proxy discard and rewrite external forwarding headers, let only internal hops append according to a trusted list, and have the application read the value exactly once through the framework’s forwarded-header integration point. Use a ThreadLocal context only with its two constraints stated: cleanup in finally, and no propagation across async boundaries. Finally, do not claim a trust boundary exists until you have thrown a spoofed XFF request at the real deployment.