Adding Zuul filters

We can also add custom filters in the Zuul microservice for implementing some cross-cutting concerns, such as security and rate-limiting. In the API Gateway components section, we discussed four filters—pre, post, route, and error. We can create these filters by extending the com.netflix.zuul.ZuulFilter class. We have to override filterType, filterOrder, and shouldFilter, and run methods. Let's see the following PreFilter custom filter:

package com.dineshonjava.apizuulservice.filters;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
public class PreFilter extends ZuulFilter{
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
if (request.getAttribute("AUTH_HEADER") == null) {
//generate or get AUTH_TOKEN, ex from Spring Session repository
String sessionId = UUID.randomUUID().toString();
ctx.addZuulRequestHeader("AUTH_HEADER", sessionId);
}
return null;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public int filterOrder() {
return 0;
}
@Override
public String filterType() {
return "pre";
}
}

In the preceding class, we have created PreFilter by extending the ZuulFilter abstract class of Netflix's Zuul API. Similarly, we can create RouteFilter, PostFilter, and ErrorFilter. You can find the complete code on the GitHub repository at https://github.com/PacktPublishing/Mastering-Spring-Boot-2.0. In the preceding filter class, we modified the run() method by adding AUTH_HEADER as a request header using RequestContext.addZuulRequestHeader(). This header will be forwarded to the internal microservices.

After creating Zuul filters, we have to register these filters with the Zuul proxy service by creating the bean definitions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.42.134