微服务之间访问经gateway无法传递token问题。

来源:10-15 进阶:再谈过滤器执行顺序

troylc

2020-03-17

大目老师:我发现脱坑经过别的位没有把这个header信息传递下去。我的案例如下:

A系统resttemplate请求访问B服务的一个地址,B服务必须是经过认证登录后,才能访问,我从A系统登录认证后,把token信息,经gateway传递到B服务,但是B服务在验证时,发现是未认证的请求,直接报401了,我怀疑是token经过gateway,没有传递给B服务

A系统请求的代码:

@GetMapping("/getDemoInfo/{demoInfo}")
@ResponseBody
public SimpleResponse<String> getInfo(@PathVariable String demoInfo,HttpServletRequest request) throws IOException {
   String access_token = CookieUtil.getToken(request, "access_token");
   String demoGetwAYUrl = "http://gateway.edianzu.cn:8100/demo/demo/testInfo/"+demoInfo;
   HttpHeaders headers = new HttpHeaders();
   headers.add("Authorization", "bearer " + access_token);
   HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(null, headers);
   ResponseEntity<SimpleResponse> returnDemoInfo = restTemplate.exchange(demoGetwAYUrl,HttpMethod.GET,entity,SimpleResponse.class);
   return returnDemoInfo.getBody();
}

以上的token是有值 的,我打出来access_token是有值的

gateway相关配置:

启动类上:

@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {

   public static void main(String[] args) {
       SpringApplication.run(GatewayApplication.class, args);
   }
}

配置信息:

spring:
 cloud:
   nacos:
     discovery:
       server-addr: 127.0.0.1:8848
   gateway:
     discovery:
       locator:
         # 让gateway通过服务发现组件找到其他的微服务
         enabled: true
         lower-case-service-id: true
 application:
   name: edz-gateway

B服务是通过启动SSO(来判断是否认证的)

@Configuration
@EnableOAuth2Sso
public class WebMvcConfig implements WebMvcConfigurer {
   @Bean(name = "redirectStrategy")
   public RedirectStrategy redirectStrategy() {
       return new DefaultRedirectStrategy();
   }
   @Override
   public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**")
               .allowedOrigins("*")
               .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
               .allowCredentials(true)
               .maxAge(7200)
               .allowedHeaders("*");
   }
}

B服务被A系统请求的地址代码如下:

@GetMapping("/testInfo/{info}")
public SimpleResponse<String> testInfo(@PathVariable("info") String info, HttpServletRequest request) {
   String access_token = CookieUtil.getToken(request, "access_token");
   log.info("=====从admin系统中访问过来====token:{}", access_token);
   return SimpleResponse.Success("获取demo的testinfo信息为:"+info);
}

如果我直接这样被A系统调用,代码都没有执行到这个地方来,直接被认证服务器拦截,报401了,

如果把这个url设置为不需要认证就可以访问,这个时候的access_token是空值。

我想知道这种方式怎么传递token.是不是因为spring cloud gateway是webflux方式的,我A系统这种请示方式gateway是接收不到header头的?

写回答

1回答

大目

2020-03-18

我的理解,你的问题应该是这样的
你先访问a登录,获得了token
然后你携带token通过网关访问a,a再调用b。
然后b没有获取到token。

这个里面,其实不是网关没有传递token,或者把你的token吃掉了,而且微服务a拿到token之后,调用b时,没有去传递给b

视频11-14    11-15节有详细讲解如何在微服务之间传递token

0
0

Spring Cloud Alibaba微服务从入门到进阶

面向未来微服务:熟练掌握Spring Cloud Alibaba

3085 学习 · 1324 问题

查看课程