Zuul网关同时管理各服务的api的访问权限,没登陆则不能调用某些接口:
使用Zuul过滤器实现:
步骤:
1、新建一个filter包
2、新建一个类,继承ZuulFilter类,在类顶部加注解@Component, 让Spring扫描
3、重写里面的4个方法,参考如下:
package net.xdclass.apigataway.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.apache.commons.lang.StringUtils; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE; /** * 登录过滤器 */ @Component public class LoginFilter extends ZuulFilter { /** * 过滤器类型,前置过滤器 * @return */ @Override public String filterType() { return PRE_TYPE; } /** * 过滤器顺序,越小越先执行 * @return */ @Override public int filterOrder() { return 4; } /** * 过滤器是否生效 * @return */ @Override public boolean shouldFilter() { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); //System.out.println(request.getRequestURI()); ///apigateway/product/api/v1/product/list //System.out.println(request.getRequestURL()); //http://localhost:9000/apigateway/product/api/v1/product/list //忽略大小写,返回true则拦截,进入run方法 if ("/apigateway/order/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())){ return true; }else if ("/apigateway/order/api/v1/order/list".equalsIgnoreCase(request.getRequestURI())){ return true; }else if ("/apigateway/order/api/v1/order/find".equalsIgnoreCase(request.getRequestURI())){ return true; } return false; } /** * 业务逻辑 * @return * @throws ZuulException */ @Override public Object run() throws ZuulException { //JWT RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); //token对象 String token = request.getHeader("token"); //如果token字符串为空 if(StringUtils.isBlank((token))){ token = request.getParameter("token"); } //登录校验逻辑 根据公司情况自定义 JWT if (StringUtils.isBlank(token)) { //设置为false则不往下走(不调用api接口) requestContext.setSendZuulResponse(false); //响应一个状态码:401 requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); } return null; } }
原文地址:https://www.cnblogs.com/big-cut-cat/p/9915276.html
时间: 2024-10-05 01:32:52