紧接着上篇随笔Spring Cloud Zuul写,添加过滤器,进行权限验证
1.添加过滤器
package com.dzpykj.filter; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; @Component public class AccessFilter extends ZuulFilter { @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); Object accessToken = request.getParameter("accessToken"); if (request.getRequestURI().contains("myOrder")) { if (accessToken == null) { ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(401); try { ctx.getResponse().getWriter().write("You are unauthorized"); } catch (IOException e) { e.printStackTrace(); } return null; } } return null; } }
2.访问http://127.0.0.1:8767/service1/myOrder;http://127.0.0.1:8767/service2/myOrder
3.源码:https://github.com/PinBo1991/springcloud
时间: 2024-10-24 19:46:50