Skip to content

Instantly share code, notes, and snippets.

@jebeaudet
Created April 21, 2016 12:49
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jebeaudet/858a7a67eacae1f2228c81cf60b3de65 to your computer and use it in GitHub Desktop.
X-Forwarded ZuulFilter
import org.eclipse.jetty.http.HttpHeader;
import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper;
import org.springframework.stereotype.Component;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
@Component
public class XForwardedHeadersPreFilter extends ZuulFilter
{
private static final String XFHOST_HEADER = HttpHeader.X_FORWARDED_HOST.toString();
private static final String XFFOR_HEADER = HttpHeader.X_FORWARDED_FOR.toString();
private static final String XFPROTO_HEADER = HttpHeader.X_FORWARDED_PROTO.toString();
private static final String XFPORT_HEADER = "X-Forwarded-Port";
private static final String[] XF_HEADERS = { XFHOST_HEADER, XFFOR_HEADER, XFPROTO_HEADER, XFPORT_HEADER };
private ProxyRequestHelper helper = new ProxyRequestHelper();
@Override
public int filterOrder()
{
return 4;
}
@Override
public String filterType()
{
return "pre";
}
@Override
public boolean shouldFilter()
{
return true;
}
@Override
public Object run()
{
RequestContext ctx = RequestContext.getCurrentContext();
int port = ctx.getRequest().getServerPort();
String clientIp = ctx.getRequest().getRemoteAddr();
String scheme = ctx.getRequest().getScheme();
ctx.addZuulRequestHeader(XFHOST_HEADER, getHostHeaderValue(ctx, scheme, port));
ctx.addZuulRequestHeader(XFFOR_HEADER, clientIp);
ctx.addZuulRequestHeader(XFPROTO_HEADER, scheme);
ctx.addZuulRequestHeader(XFPORT_HEADER, String.valueOf(port));
//This will make sure that the original headers are not passed down the chain
helper.addIgnoredHeaders(XF_HEADERS);
return null;
}
private String getHostHeaderValue(RequestContext ctx,
String scheme,
int port)
{
String host = ctx.getRequest().getServerName();
if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
host = String.format("%s:%d", host, port);
}
return host;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment