亲宝软件园·资讯

展开

SpringCloud Zuul过滤器 SpringCloud Zuul过滤器实现登陆鉴权代码实例

Catbir 人气:0

1.新建一个filter‘包

2.新建一个类,实现ZuulFilter,重写里面的方法

3.在顶部类添加注解,@Component,让Spring扫描

/**
 * 登陆过滤器
 */
@Component
public class LoginFilter extends ZuulFilter {
  @Override
  public String filterType() { //前置过滤器
    return PRE_TYPE;
  }

  @Override
  public int filterOrder() { //过滤器顺序,越小越先执行
    return 3;
  }

  @Override
  public boolean shouldFilter() { //过滤器是否生效
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    System.out.println(request.getRequestURI());
    System.out.println(request.getRequestURL());
    if ("/apizuul/order/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())){ //拦截
      return true;
    }
    return false;
  }

  /**
   * 业务逻辑
   * @return
   * @throws ZuulException
   */
  @Override
  public Object run() throws ZuulException {
    System.out.println("拦截...");
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    String token = request.getHeader("token");
    if (StringUtils.isBlank(token)){
      token = request.getParameter("token");
    }
    //登陆校验逻辑 jwt生成token
    if (StringUtils.isBlank(token)){
      requestContext.setSendZuulResponse(false); //不会往下执行
      requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
    }
    return null;
  }

加载全部内容

相关教程
猜你喜欢
用户评论