xiangyangsanren
fly_烟雨行舟
2019-02-07 01:48

Zuul过滤器里面用addZuulRequestHeader转发没有作用

  • spring
  • java
  • java-ee

springcloud版本:Finchley SR2

1、引入依赖

                <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>

2、zuul配置

zuul:
  routes:
    app-user:
      path: /user/**
      serviceId: app-user

3、过滤器

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

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

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

    @Override
    public Object run() throws ZuulException {
        System.out.println("zuul过滤器...");
        //向header中添加鉴权令牌
        RequestContext requestContext = RequestContext.getCurrentContext();
        //获取header
        HttpServletRequest request = requestContext.getRequest();
        String authorization = request.getHeader("Authorization");
        if(authorization != null) {
            System.out.println("authorization: " + authorization);
            requestContext.addZuulRequestHeader("Authorization", authorization);
        }
        return null;
    }
}

4、在app-user服务的controller里面测试能否获取到

@Autowired
    private HttpServletRequest request;

    /**
     * 查询全部数据
     * @return
     */
    @RequestMapping(method= RequestMethod.GET)
    public Result findAll(){
        String header = request.getHeader("Authorization");
        System.out.println("authHeader: " + header);
        return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
    }

5、结果
1)、在过滤器里面能拿到,并且打印有值;
2)、在controller里面测试获取不到,打印为null。

PS:
不知道为什么在过滤器里这个addZuulRequestHeader没起作用,折腾半天没找原因,甚至查找了一些博客,写法都一样的,就那么几步,有哪位大佬遇到过这问题的,可以给点思路吗……┭┮﹏┭┮

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

7条回答

为你推荐