Springboot:将从swagger UI捕获的JWT令牌自动传递到下游(服务到服务)API调用

问题描述 投票:1回答:1

我在寻找什么:-

  1. 将JWT令牌传递给从swagger-ui(springfox)实现中捕获的下游API调用(服务到服务的调用)。

有没有办法达到相同的效果?

注意:-我将从Swagger-ui捕获令牌

spring-boot spring-mvc swagger swagger-ui springfox
1个回答
0
投票

在springboot应用程序中,如果要将JWT令牌传递给另一个REST api,通常的方法是将其通过标头传递。在springboot应用程序中,您可以配置rest模板bean,使其在应用程序的每个请求中都包含JWT令牌。例如,您可以创建一个rest模板bean,如:

@Component
public class RestTemplateConfig {

  @Bean
  @RequestScope
  public RestTemplate keycloakRestTemplate(HttpServletRequest inReq) {
    // retrieve the auth header from incoming request
    final String authHeader = 
      inReq.getHeader(HttpHeaders.AUTHORIZATION);
    final RestTemplate restTemplate = new RestTemplate();
    // add a token if an incoming auth header exists, only
    if (authHeader != null && !authHeader.isEmpty()) {
      // since the header should be added to each outgoing request,
      // add an interceptor that handles this.
      restTemplate.getInterceptors().add(
        (outReq, bytes, clientHttpReqExec) -> {
          outReq.getHeaders().set(
            HttpHeaders.AUTHORIZATION, authHeader
          );
          return clientHttpReqExec.execute(outReq, bytes);
        });
    }
    return restTemplate;
  }
}

然后,您可以在各处使用相同的rest模板bean。这里提供了另一种方法:Propagate HTTP header (JWT Token) over services using spring rest template

© www.soinside.com 2019 - 2024. All rights reserved.