标签:ade The div system sdn tar 作用 map ram
大家应该都知道在做Zuul网关过滤的时候,如果不在网关过滤时转发头信息,经过网关时头信息就会丢失。
但我用 addZuulRequestHeader转发头信息时,却不起作用,在子服务的controller取不到头信息的内容,代码如下:
1、引入依赖
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework.cloud</groupId> 4 <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> 5 </dependency> 6 <dependency> 7 <groupId>org.springframework.cloud</groupId> 8 <artifactId>spring-cloud-starter-netflix-zuul</artifactId> 9 </dependency> 10 </dependencies>
2、zuul配置
1 zuul: 2 routes: 3 xxxx-base: 4 path: /base/** 5 serviceId: xxxx-base
3、过滤器
import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; @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 { //得到request上下文 RequestContext currentContext = RequestContext.getCurrentContext(); //得到request域 HttpServletRequest request = currentContext.getRequest(); //得到头信息 String header = request.getHeader("Authorization"); //判断是否有头信息 if(header != null && !"".equals(header)){ //把头信息继续向下传 currentContext.addZuulRequestHeader("Authorization", header); } return null; } }
4、在xxxx-user服务的controller里面测试能否获取到
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController @CrossOrigin @RequestMapping("/label") public class LabelController { @Autowired private LabelService labelService; @Autowired private HttpServletRequest request; @GetMapping public Result findAll(){ //获取头 String header= request.getHeader("Authorization"); System.out.println("++++++++++++++:"+header); return new Result(true, StatusCode.OK,"查询成功",labelService.findAll()); } }
5、结果
1)、在过滤器里面能拿到,并且打印有值;
2)、在controller里面测试获取不到,打印为null。
最终在网上看到一个兄弟的博客,才找出问题所在,
原来是因为头信息的Authorization这个单词的问题
敏感头信息Authorization,Cookie,Set-Cookie默认是不转发的,也就获取不到
在配置文件里设置zuul.sensitiveHeaders为空,或者使用别的单词如Authorization1,就可以获取到了
万分感谢!贴上原文地址 https://ask.csdn.net/questions/748656?sort=id
标签:ade The div system sdn tar 作用 map ram
原文地址:https://www.cnblogs.com/mww-NOTCOPY/p/11182363.html