Spring Cloud Building MicroServices Architecture-Service Gateway Filter

Source: Internet
Author: User

Filter action
The interface provided by our MicroServices application can be accessed by the client through a unified API Gateway portal. However, when each client user requests the interface provided by the MicroServices application, their access is often limited, and the system does not open all of the microservices interfaces to them. However, the current service routing does not have the ability to restrict permissions, all requests are unreservedly forwarded to the specific application and return results, in order to achieve the client request Security check and permission control, The simplest and most brutal approach is to implement a filter or interceptor for each microservices application that verifies the signature and authentication permissions.
However, this is not advisable, it will increase the future of system maintenance difficulty, because the same system of various check logic is roughly the same or similar, so that the implementation of similar verification logic code is scattered across the micro-services, redundant code appears we do not want to see. Therefore, it is better to take these check logic out of the way and build an independent authentication service. After the split, many developers will directly in the micro-service application by invoking the authentication service to achieve the verification, but this is only to solve the separation of the authentication logic, and did not in essence this part of the logic does not belong to the original micro-service application, redundant interceptors or filters will still exist.
For such a problem, it is better to perform these non-business checks by using the Gateway Service in front of you. Because the Gateway service joins, the external client accesses our system already has the unified entrance, since these checks are not related to the specific business, then does not have to complete the checksum filtering when the request arrives, but is not forwards after the filtering and causes the longer request delay. At the same time, by completing the checksum filtering in the gateway, the micro-service application can remove all kinds of complex filters and interceptors, which makes the interface development and testing complexity of the micro-service application be reduced correspondingly.
To enable validation of client requests in the API gateway, we will need to use another core feature of spring Cloud Zuul: Filters.
Zuul allows developers to implement the interception and filtering of requests by defining filters on the API gateway, and implementing the method is very simple, we only need to inherit the Zuulfilter abstract class and implement the four abstract functions defined by it to complete the interception and filtering of the request.
Implementation of filters
For example, the following code, we define a simple Zuul filter, it implements the request is routed before the check whether there are accesstoken parameters, if there is a route, if not denied access, return 401 Unauthorized error.

public class AccessFilter extends ZuulFilter {private static Logger log = LoggerFactory.getLogger(AccessFilter.class);@Overridepublic String filterType() {return "pre";}@Overridepublic int filterOrder() {return 0;}@Overridepublic boolean shouldFilter() {return true;}@Overridepublic Object run() {RequestContext ctx = RequestContext.getCurrentContext();HttpServletRequest request = ctx.getRequest();log.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());Object accessToken = request.getParameter("accessToken");if(accessToken == null) {log.warn("access token is empty");ctx.setSendZuulResponse(false);ctx.setResponseStatusCode(401);return null;}log.info("access token ok");return null;}}

In the filter code implemented above, we implement a custom filter by inheriting the Zuulfilter abstract class and re-writing the following four methods. These four methods respectively define the following:

FilterType: The type of filter that determines which life cycle the filter executes in the request. This is defined as the pre, and the delegate executes before the request is routed.
Filterorder: The order in which the filters are executed. When a request has multiple filters in one phase, it needs to be executed sequentially based on the value returned by the method.
Shouldfilter: Determine if the filter needs to be executed. Here we directly return true, so the filter will take effect for all requests. In practice we can use this function to specify the effective range of the filter.
Run: The specific logic of the filter. Here we use Ctx.setsendzuulresponse (false) to make Zuul filter the request, do not route it, and then set its return error code via CTX.SETRESPONSESTATUSCODE (401). Of course, we can also further optimize our return, for example, by Ctx.setresponsebody (body) to return the body content to edit and so on.
After implementing a custom filter, it does not take effect directly, and we also need to create a specific bean for it to start the filter, for example, add the following in the application main class:

@EnableZuulProxy@SpringCloudApplicationpublic class Application {public static void main(String[] args) {new SpringApplicationBuilder(Application.class).web(true).run(args);}@Beanpublic AccessFilter accessFilter() {return new AccessFilter();}}

Here, the basic functionality of the spring Cloud Zuul filter is described. According to their own needs, the reader can define some general-purpose logic to implement the filtering and interception of the request, such as signature check, permission check, request current limit and so on service gateway.

From now on, I will record the process and the essence of the recently developed Springcloud micro-service cloud architecture, and help more friends who are interested in developing the Spring cloud framework, hoping to help more good scholars. Let's explore how the Spring cloud architecture is built and how it can be used in enterprise projects.

Spring Cloud Building MicroServices Architecture-Service Gateway Filter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.