Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PROXY_KEY;
/**
* Adds an API key in the form of a request header to proxied requests.
* You have to specify a prefix for the name of the Zuul proxy to match,
* as we don't want to add these headers to requests made to other downstream services.
*/
public class ApiKeyHeaderFilter extends ZuulFilter {
private String headerName = "Ocp-Apim-Subscription-Key";
private String proxyPrefix;
private String apiKey;
public ApiKeyHeaderFilter(String proxyPrefix, String apiKey) {
this.proxyPrefix = proxyPrefix;
this.apiKey = apiKey;
}
/**
* Default header name is {@code Ocp-Apim-Subscription-Key} as used by Microsoft Azure.
*
* @param headerName name of the header to contains the API key
*/
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return PRE_DECORATION_FILTER_ORDER + 1;
}
@Override
public boolean shouldFilter() {
// only filter for the matching proxy, or we could accidentally expose secrets to other downstream services
RequestContext currentContext = RequestContext.getCurrentContext();
String currentProxy = (String) currentContext.get(PROXY_KEY);
return currentProxy != null && currentProxy.startsWith(proxyPrefix);
}
@Override
public Object run() throws ZuulException {
RequestContext currentContext = RequestContext.getCurrentContext();
currentContext.addZuulRequestHeader(headerName, apiKey);
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment