问题描述
有时候系统的功能并不对外开放,所以在请求服务时可以过滤掉非法请求。Zuul通过ZuulFilter过滤器实现,每次经过Zuul服务网关,我们都对带来的token进行有效性验证,验证不通过就无法请求成功
配置过程
定义过滤类
命名为:AccessFilter.java,继承ZuulFilter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| package com.ledao.filter;
import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
public class AccessFilter extends ZuulFilter {
Logger logger = LoggerFactory.getLogger(AccessFilter.class);
@Override public String filterType() { return "pre"; }
@Override public int filterOrder() { return 0; }
@Override public boolean shouldFilter() { return true; }
@Override public Object run() throws ZuulException { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); String parameter = request.getParameter("accessToken"); logger.info(request.getRequestURI() + "请求访问"); if (parameter == null) { logger.error("accessToken为空!"); requestContext.setSendZuulResponse(false); requestContext.setResponseStatusCode(401); requestContext.setResponseBody("{\"result\":\"accessToken is empty!\"}"); return null; } logger.info(request.getRequestURI() + "请求成功"); return null; } }
|
开启Filter配置
新建一个类,命名为:ZuulConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.ledao.config;
import com.ledao.filter.AccessFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class ZuulConfig {
@Bean public AccessFilter accessFilter() { return new AccessFilter(); } }
|
结果
直接输入:http://zuul.ledao.com:3001/ledao/studentServer/student/list ,请求失败,返回错误信息:{“result”: “accessToken is empty!”}
加上?accessToken=111,即:http://zuul.ledao.com:3001/ledao/studentServer/student/list?accessToken=111 ,请求成功,返回正确的数据
本文主要是实现过滤配置,上面只是模拟了有accessToken