一、项目架构图
二、前置过滤器
@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 requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest(); //这里从url参数获取,也可以从cookie,header里获取
String token = request.getParameter("token");
if(StringUtils.isEmpty(token)){
//不通过
requestContext.setSendZuulResponse(false);
requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
}
return null;
}
}
带了token就能正常访问
否则,无法访问,返回401
三、后置过滤器
1、增加后置过滤器
@Component
public class AddResponseHeaderFilter extends ZuulFilter {
@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;
}
}
在回复后里增加X-Foo,值为UUID
2、查看结果