(1)Pre过滤器
第一步,说明是Component并且继承自ZuulFilter:
@Component
public class TokenFilter extends ZuulFilter
第二步实现抽象方法:
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return PRE_DECORATION_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext currentContext = RequestContext.getCurrentContext();
HttpServletRequest request = currentContext.getRequest();
//这里是从url参数里获取,也可以从cookie,header里获取
String token = request.getParameter("token");
if(StringUtils.isEmpty(token)) {
currentContext.setSendZuulResponse(false);
//权限不足一般写401,也可以这么写
// currentContext.setResponseStatusCode(401);
currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
}
return null;
}
这样的前置过滤器可以实现,如果没有token,就不能访问相关页面。
(2)Post过滤器
与pre过滤器基本一致,实现的抽象方法有所不同:
@Override
public String filterType() {
return POST_TYPE;
}
@Override
public int filterOrder() {
return SEND_RESPONSE_FILTER_ORDER -1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletResponse response = requestContext.getResponse();
response.setHeader("X-Foo", UUID.randomUUID().toString());
return null;
}