DEVYANSH MITTAL
DEVYANSH MITTAL

Reputation: 45

Springboot: Pass the JWT token captured from swagger UI to the downstream(Service to service) API calls automatically

What i am looking for :-

  1. Pass the JWT token to the downstream API calls (service to service calls) captured from swagger-ui (springfox) implementation.

Is there way to achieve the same.?

Note:- I am to capture the token from the Swagger-ui

Upvotes: 1

Views: 720

Answers (1)

Ananthapadmanabhan
Ananthapadmanabhan

Reputation: 6216

In your springboot application , if you want to pass a JWT token to another REST api, the general approach is to pass it through headers. In your springboot application, you could configure your rest template bean to include the JWT token in every request from your application.For instance , you could create a rest template bean like :

@Configuration
public class RestTemplateConfig {

  @Bean
  @RequestScope
  public RestTemplate authTokenAddedRestTemplate(HttpServletRequest inReq) {

    final String authHeader = 
      inReq.getHeader(HttpHeaders.AUTHORIZATION);
    final RestTemplate restTemplate = new RestTemplate();

    if (authHeader != null && !authHeader.isEmpty()) {

      restTemplate.getInterceptors().add(
        (outReq, bytes, clientHttpReqExec) -> {
          outReq.getHeaders().set(
            HttpHeaders.AUTHORIZATION, authHeader
          );
          return clientHttpReqExec.execute(outReq, bytes);
        });
    }
    return restTemplate;
  }
}

Then you could use the same rest template bean everywhere. Another approach is provided here : Propagate HTTP header (JWT Token) over services using spring rest template

Upvotes: 1

Related Questions