• spring cloud 服务A调用服务B自定义token消失,记录


    后端:spring cloud

    前端:vue

    场景:前端ajax请求,包装自定义请求头token到后台做验证,首先调用A服务,A服务通过Feign调用B服务发现自定义token没有传到B服务去;

    原因:cloud 服务之间的调用都是基于Feign的,所以我们可以在调用之前做一些事情,在请求头header中添加自定义请求头token

    首先定义一个feign的拦截器,达到在发送请求前认证token的目的'

    定义一个配置类

    @Configuration // 说明该类是配置类
    public class FeignConfiguration {
    
        /**
         * 创建Feign请求拦截器,在发送请求前设置认证的token,各个微服务将token设置到环境变量中来达到通用
         * @return
         */
        @Bean
        public FeignBasicAuthRequestInterceptor basicAuthRequestInterceptor() {
            return new FeignBasicAuthRequestInterceptor();
        }
    
    
    
    
    }
    

      

    FeignBasicAuthRequestInterceptor 实现RequestInterceptor 接口;RequestInterceptor是feign的拦截器,实现里面的apply方法

     public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
    
            public FeignBasicAuthRequestInterceptor(){
    
            }
    
            @Override
            public void apply(RequestTemplate requestTemplate) {
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()){
                        String name = headerNames.nextElement();
                        Enumeration<String> values = request.getHeaders(name);
                        while (values.hasMoreElements()) {
                            String value = values.nextElement();
                            requestTemplate.header(name, value);
                        }
                    }
                }
            }
        }
    

      

     注意,在改完以上的部分可能还不生效,需要在A服务的yml文件中添加

    hystrix:
      command:
        default:
          execution:
            isolation:
              strategy: SEMAPHORE

    如果B服务还要调用其他的服务C,在B服务的yml文件中也需要加上改配置

    
    
    
  • 相关阅读:
    学区房概念
    VMwareworkstationfull8.0.2591240.exe
    VMwareworkstationfull8.0.4744019.exe
    .net伪静态
    将DataTable中的某一行复制到另一个新的DataTable(转)
    js服务器端控件Label 与TextBox RadioButtonList 与 DropDownList 的值
    Iframe刷新父窗口的几种方式
    记录一下ListItem类的常用的方法
    ASP.net中的Repeater控件嵌套
    记录一条自己常用的分页存储过程
  • 原文地址:https://www.cnblogs.com/wangjinyu/p/10300680.html
Copyright © 2020-2023  润新知