springcloud feign 添加请求头 转发请求头

转发请求头

@Configuration
public class FeignConfiguration {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attrs != null) {
                HttpServletRequest request = attrs.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String value = request.getHeader(name);
                        /**
                         * 遍历请求头里面的属性字段,将logId和token添加到新的请求头中转发到下游服务
                         * */
                        requestTemplate.header(name, value);
                    }
                } 
            }
        };
    }
}

存在问题

在gateway服务中无法获取HttpServletRequest,暂时没解决

gateway中添加凭证请求头

添加basic认证

@Configuration
public class IRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        if(requestTemplate.path().startsWith("/oauth")){
            //auth服务
            String authorization = "Basic "+ Base64.getEncoder().encodeToString("xxx:xxxx".getBytes());
            //添加认证请求头
            requestTemplate.header("Authorization", authorization);
        }
    }
}
发表新评论