简体   繁体   English

Spring Cloud Zuul:仅对特定路由应用过滤器

[英]Spring Cloud Zuul: Apply filter only to specific route

I'm using Spring Cloud's Zuul to proxy some API requests to a few external servers.我正在使用 Spring Cloud 的 Zuul 将一些 API 请求代理到一些外部服务器。 The proxying itself works well, but each service requires a (different) token provided in the request header.代理本身运行良好,但每个服务都需要在请求标头中提供一个(不同的)令牌。

I've successfully written a simple pre filter for each token that applies the appropriate header.我已经成功地为每个应用适当标头的令牌编写了一个简单的预过滤器。 However, I now have a problem.但是,我现在有一个问题。 Even after pouring through the documentation, I can't figure out how to make each filter apply only to the proper route.即使在翻阅文档之后,我也无法弄清楚如何使每个过滤器仅适用于正确的路线。 I don't want to perform url-matching as the url changes across environments.我不想在 url 跨环境更改时执行 url 匹配。 Ideally, I'd have some way to get the name of the route in the filter.理想情况下,我有一些方法可以在过滤器中获取路线的名称。

My application.yml:我的应用程序.yml:

zuul:
  routes:
    foo:
      path: /foo/**
      url: https://fooserver.com
    bar:
      path: /bar/**
      url: https://barserver.com

Ideally I'd like to do something like this in FooFilter.java (a prefilter):理想情况下,我想在 FooFilter.java (预过滤器)中做这样的事情:

public bool shouldFilter() {
    return RequestContext.getCurrentContext().getRouteName().equals("foo");
}

but I can't seem to find any way to do this.但我似乎找不到任何方法来做到这一点。

You can use proxy header in RequestContext to distinguish routed server like below.您可以在RequestContext使用proxy标头来区分路由服务器,如下所示。 If you are using ribbon, you can also use serviceId header.如果您使用功能区,您还可以使用serviceId标头。 But if you specify url direclty like above your example, you should use proxy header.但是,如果您像上面的示例一样指定 url direclty,则应该使用proxy标头。 One thing you have to know is that proxy header is set in PreDecorationFilter , so your pre-filter must have bigger value of filter order than the value that PreDecorationFilter has (it is 5 at this moment).您必须知道的一件事是在PreDecorationFilter设置了proxy标头,因此您的预过滤器的过滤顺序值必须大于PreDecorationFilter的值(此时为 5)。

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

@Override
public boolean shouldFilter() {
    RequestContext ctx = RequestContext.getCurrentContext();

    if ((ctx.get("proxy") != null) && ctx.get("proxy").equals("foo")) {
        return true;
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM