大目老师:我发现脱坑经过别的位没有把这个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头的?
面向未来微服务:熟练掌握Spring Cloud Alibaba
了解课程