SpringCloud之Zuul过滤器实现登录鉴权实战
自定义zuul过滤器实现登录鉴权实战
1、新建filter包
1 /** 2 * @author WGR 3 * @create 2019/10/20 -- 21:19 4 */ 5 /** 6 * 登录过滤器 7 */ 8 @Component 9 public class LoginFilter extends ZuulFilter { 10 11 /** 12 * 过滤器类型,前置过滤器 13 * @return 14 */ 15 @Override 16 public String filterType() { 17 return "pre"; 18 } 19 20 /** 21 * 过滤器顺序,越小越先执行 22 * @return 23 */ 24 @Override 25 public int filterOrder() { 26 27 return 4; 28 } 29 30 31 /** 32 * 过滤器是否生效 33 * @return 34 */ 35 @Override 36 public boolean shouldFilter() { 37 38 RequestContext requestContext = RequestContext.getCurrentContext(); 39 HttpServletRequest request = requestContext.getRequest(); 40 41 //System.out.println(request.getRequestURI()); ///apigateway/product/api/v1/product/list 42 //System.out.println(request.getRequestURL()); //http://localhost:9000/apigateway/product/api/v1/product/list 43 44 //ACL 45 46 if ("/apigateway/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())){ 47 return true; 48 }else if ("/apigateway/order/api/v1/order/list".equalsIgnoreCase(request.getRequestURI())){ 49 return true; 50 }else if ("/apigateway/order/api/v1/order/find".equalsIgnoreCase(request.getRequestURI())){ 51 return true; 52 } 53 54 return false; 55 } 56 57 /** 58 * 业务逻辑 59 * @return 60 * @throws ZuulException 61 */ 62 @Override 63 public Object run() throws ZuulException { 64 65 //JWT 66 RequestContext requestContext = RequestContext.getCurrentContext(); 67 HttpServletRequest request = requestContext.getRequest(); 68 69 //token对象 70 String token = request.getHeader("token"); 71 72 if(StringUtils.isBlank((token))){ 73 token = request.getParameter("token"); 74 } 75 76 77 //登录校验逻辑 根据公司情况自定义 JWT 78 if (StringUtils.isBlank(token)) { 79 requestContext.setSendZuulResponse(false); 80 requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); 81 } 82 83 return null; 84 } 85 86 87 88 }
测试:
-
不带token
-
带token