(J) the service gateway Zuul (filter)

I. Introduction

In the last article , we learned about Spring Cloud Zuul as a gateway with the most basic functions: Routing (Router). In this article we will focus on other core functions of Spring Cloud Zuul's: filter (Filter).

Filter effects

We have been able to achieve routing requests, so the interface of our micro-services provided by the application can be through a unified API gateway entry is client access to.
However, each client service requested by the user interface microcircuit applications, which often require access to certain restrictions , the system does not take all of the micro-service interfaces are open to them. However, the current service routing function does not limit such rights, without reservation, all requests will be forwarded to a specific application and returns the result.
In order to achieve the security check and control the permissions requested by the client, the most simple and brutal way is for each service application implements micro filter or interceptor to verify the signature and identify a set of permissions. However, this approach is not desirable, it will increase the difficulty of maintaining the system in the future, as a system under the same variety of validation logic in many cases are substantially the same or similar, such implementation would make a similar check logic code is distributed to the various services to micro, appears redundant code is that we do not want to see. Therefore, good practice is to spin off the checking logic to construct a separate authentication service. After completion of the separation, many developers will be directly in the micro-service applications to achieve parity by calling the authentication service, but such an approach is just to solve the separation of authentication logic, and this part is not, in essence, amateur not split the original logical micro service applications, redundant blocker or filter still exist.

For such problems, a better approach is to verify the completion of these non-operational nature through the front of the gateway service . Since the addition of gateway services, external clients have access to our system unified entrance, since the check has nothing to do with the specific business, why not complete at the time of check and filter incoming requests rather than forward then filtered caused request a longer delay. Meanwhile, by performing checksums, microfiltration service gateway application side can be removed in a variety of complex filters and the interceptor , which makes the complexity of interface development and testing of micro service application has also been reduced accordingly.

To achieve the check on the client requests the API gateway, we will need to use another Spring Cloud Zuul core functions: the filter .

Zuul allows developers to implement the API gateway intercepts the request and filtered through a filter defined, the method is very simple to achieve.

 

 

Two, Filter life cycle

Filter life cycle has four, namely, "PRE", "ROUTING", "POST" and "ERROR", the entire life cycle can be represented by the following FIG.

Zuul most of the functions are implemented by a filter, these types of filters corresponding to the typical life cycle of the request.

  • PRE: This filter is called before the request is routed. We can use this filter for authentication, select the request in the cluster micro service record debugging information.
  • ROUTING: This filter routes the request to the micro-service. This filter is used to construct the service request sent to the micro, and or using Apache HttpClient Netfilx Ribbon micro service request.
  • POST: This filter is performed after the service is routed to the micro. Such a filter response may be used to add standard HTTP Header, collecting statistics and indicators, the response is sent from the micro-services to clients.
  • ERROR: the implementation of the filter when other stages errors. In addition to the default filter type, Zuul also allows us to create a custom filter type. For example, we can have customized a STATIC type of filter, generated in response Zuul directly, without the rear forwards the request to the micro-services.

 

 

Three, Zuul realization of default Filter

Types of order filter Features
pre -3 ServletDetectionFilter Marking process Servlet type
pre -2 Servlet30WrapperFilter Packing HttpServletRequest request
pre -1 FormBodyWrapperFilter Packing request body
route 1 DebugFilter Mark debug flag
route 5 PreDecorationFilter Processing request context for subsequent use
route 10 RibbonRoutingFilter serviceId request forwarding
route 100 SimpleHostRoutingFilter url request forwarding
route 500 SendForwardFilter forward the request to forward
post 0 Send Error Filter Error processing request response
post 1000 SendResponseFilter Normal processing request response

 

 

Fourth, disable specified Filter

You can configure the application.yml need to disable the filter, format  zuul.<SimpleClassName>.<filterType>.disable=true.
For example, to disable  org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter is set

zuul:
  SendResponseFilter:
    post:
      disable: true

 

 

Fifth, Custom Filter

We assume that there is such a scene, because the service is the gateway to deal with all requests outside, in order to avoid security risks, we need to do to request certain restrictions, such as the request contains Token let requests continue to go down, if the request without Token direct return and give tips.

On the blog post projects, a first custom Filter, ZuulFilter abstract class inheritance, the run () method to verify whether the parameters contained in the Token, as follows:

package com.example.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName TokenFilter
 * @Description TODO
 * @Author lhw
 * @Date 2020/3/21 13:59
 * @Version 1.0
 **/
public class TokenFilter extends ZuulFilter {
    /**
     * 过滤器的类型,它决定过滤器在请求的哪个生命周期中执行。
     * 这里定义为pre,代表会在请求被路由之前执行。
     * @return java.lang.String
     **/
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * filter执行顺序,通过数字指定
     * 数字越大,优先级越低
     * @return int
     **/
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断该过滤器是否需要被执行。这里我们直接返回了true,因此该过滤器对所有请求都会生效。
     * 实际运用中我们可以利用函数来指定过滤器的有效范围。
     * @return boolean
     **/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑
     * @return java.lang.Object
     **/
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        if(token==null || token.isEmpty()){
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("token is empty");
        }
        return null;
    }
}

The filter implemented in the code above, we inherit  ZuulFilter the abstract class and override the following four methods to implement custom filters. These four methods were defined:

  • filterType(): Type of filter, which filters the implementation of the decision in which the life cycle of the request. Defined here as the  prerepresentatives will be executed before the request is routed.
  • filterOrder(): Execution order filters. When there is a request in a multiple stage filter, needs to be sequentially executed according to the value returned by the method. Digital designated, the larger the number, the lower the priority.
  • shouldFilter(): Determining whether the filter needs to be performed. Here we return directly  true, so the filter takes effect on all requests. Practical application we can use this function to specify a valid range filter.
  • run(): The specified logical filter. Here we pass  ctx.setSendZuulResponse(false) filtering Zuul make the request, do not be routed, and then  ctx.setResponseStatusCode(401) set the wrong code it returns, of course, we can further optimize our return, for example, by  ctx.setResponseBody(body) editing the return body content.

 

In the realization of custom filters, it does not directly take effect, we also need to create a specific Bean to start the filter, for example, an increase in the application of the following main category:

package com.example.apigateway;

import com.example.apigateway.filter.TokenFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;

@EnableZuulProxy
@SpringBootApplication
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

    @Bean
    public TokenFilter tokenFilter(){
        return new TokenFilter();
    }
}

 

Out of  api-gateway After the service completed the transformation of the above, we can re-start it, and initiate the following request, the filter defined above to do a validation:

We can define according to their needs in the service gateway of some non-business logic implementation of the general request filtering and blocking, such as: signature verification, verification authority, requesting limiting functions.

Published 111 original articles · won praise 1 · views 5439

Guess you like

Origin blog.csdn.net/daziyuanazhen/article/details/105009251