如何编写 netflix zuul 过滤器来更改响应位置 header 属性?

how can I write netflix zuul filter to change response location header attribute?

我有重定向到 x.jsp 的下游服务,例如这个位置不在网关路由中

gateway route --- localhost:8080/app - 192.168.1.1:80 (DownStream app)

在 DownStream 应用程序中,当用户未登录时,它会重定向到 192.168.1.1:80/Login.jsp,它在响应的 Location header 中。

此 URL 未使用网关。

我想编写一个 zuul 过滤器来更改此重定向 url,方法是在 zuul 路由动态中进行映射,例如对于每个 url,zuul 过滤器中的路由更改 Location [=24] =] 由网关。我该怎么做?

您的下游应用程序应遵守 x-forwarded-* headers,而不是生成那样的重定向。但是以下过滤器无论如何都会为您更改重定向位置:

@Override
public String filterType() {
    return "post";
}

@Override
public int filterOrder() {
    return 0;
}

@Override
public boolean shouldFilter() {
    int status = RequestContext.getCurrentContext().getResponseStatusCode();
    return status >= 300 && status < 400;
}

@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    Map<String, String> requestHeaders = ctx.getZuulRequestHeaders();
    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
                .stream()
                .filter(stringStringPair -> LOCATION.equals(stringStringPair.first()))
                .findFirst();

        if (locationHeader.isPresent()) {
            String oldLocation = locationHeader.get().second();
            String newLocation = ...
            locationHeader.get().setSecond(newLocation);
        }
    return null;
}