SpringCloud学习笔记(19)----Spring Cloud Netflix之服务网关Zuul自定义过滤器

  zuul不仅只是路由,还可以自定义过滤器来实现服务验证。

  实现案例:自定义过滤器,检验头部是否带有token,如果token=wangx,则通过校验,若不存在或不为wangx则返回提示token错误。

  扩展:一般情况下,可以采用JWT规范来做token的校验。

  JWT:https://jwt.io/

1. 自定义过滤器

package com.wangx.cloud.springcloud04zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        //获取requestContext实例
        RequestContext requestContext = RequestContext.getCurrentContext();
        //获取到request对象
        HttpServletRequest request = requestContext.getRequest();

        //获取response对象

        HttpServletResponse response = requestContext.getResponse();
        // 判断token是否为wangx, 1 继续往下执行,否则打印token error
        if (!"wangx".equals(request.getHeader("token"))) {
            try {
                //输出流中写入错误信息
                PrintWriter printWriter = response.getWriter();
                printWriter.write("token is error");
                printWriter.flush();
                printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("请求路径为:---" + request.getRequestURI());
        return null;
    }
}

2. 注册自定义的过滤器

 @Bean
    public MyFilter myFilter() {
        return new MyFilter();
    }

3. 测试

  使用postman访问:http://localhost:9876/spring-cloud-consumer/user/1

  

 

 

  

posted @ 2018-10-29 13:55  Eternally_dream  阅读(179)  评论(0编辑  收藏  举报