RemoteAddressFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; request = new HttpServletRequestWrapper(httpRequest) { @Override public String getRemoteAddr() { String xForwardedFor = httpRequest.getHeader(X_FORWARDED_FOR); if (xForwardedFor != null) { log.debug("Request included {} address: {}", X_FORWARDED_FOR, xForwardedFor); return xForwardedFor; } String remoteAddr = httpRequest.getRemoteAddr(); log.debug("Request did not include {} address, falling back to remote address: {}", X_FORWARDED_FOR, remoteAddr); return remoteAddr; } }; } chain.doFilter(request, response); }  @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void init(FilterConfig filterConfig); @Override void destroy();  }
@Test public void notAnHttpServletRequest() throws Exception { ServletRequest request = mock(ServletRequest.class); underTest.doFilter(request, response, chain); verify(chain).doFilter(request, response); }
@Test public void prioritiseXForwardedForHeader() throws Exception { underTest.doFilter(request, response, chain); verify(chain).doFilter(captor.capture(), eq(response)); HttpServletRequest captured = captor.getValue(); when(request.getHeader("x-forwarded-for")).thenReturn("1.2.3.4"); assertThat(captured.getRemoteAddr(), is("1.2.3.4")); }
@Test public void fallbackToRemoteAddress() throws Exception { underTest.doFilter(request, response, chain); verify(chain).doFilter(captor.capture(), eq(response)); HttpServletRequest captured = captor.getValue(); when(request.getRemoteAddr()).thenReturn("4.3.2.1"); assertThat(captured.getRemoteAddr(), is("4.3.2.1")); }