zoukankan      html  css  js  c++  java
  • 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文件中也需要加上改配置

    
    
    
  • 相关阅读:
    虚方法和抽象方法
    c#_实现FTP方法(一) FtpWebRequest
    sql server 分页
    5ucms进阶
    图片处理函数
    [转]C++11新特性:Lambda函数
    [STL]for_each详细用法[转]
    [算法]hash table 与 hash map 实现
    [算法]字典树
    [STL]vector的使用[转]
  • 原文地址:https://www.cnblogs.com/wangjinyu/p/10300680.html
Copyright © 2011-2022 走看看