We have a microservice architecture with one of the microservices having a Spring Batch job which processes a CSV file and calling another microservice. Both microservices are OAuth2 protected ResourceServers. When we call the first microservice, a batch job is started and we want the Authorization header to be passed to the second microservice. The solution can be defined as: In a Feign RequestInterceptor, grab the current OAuth access_token and pass it on the the RequestTemplate with Hystrix running in SEMAPHORE execution isolation strategy

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableResourceServer
@EnableOAuth2Client
public class MyApplication {

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

Define Job execution

@RestController
@RequiredArgsController
public class RunMyJobController {
  private final JobLauncher jobLauncher;
  private final Job myJob;
  private final OAuth2ClientContext oauth2ClientContext;

  @RequestMapping(method = RequestMethod.POST)
  public void startJob() {
    JobParametersBuilder parametersBuilder = new JobParametersBuilder();
    //Run the job.
    JobExecution jobExecution =
      jobLauncher.run(myJob, parametersBuilder.toJobParameters());

    //Here you can evaluate the job result and
    //send the proper return to the client.
  }
}

RequestInterceptor

@Configuration
@ComponentScan
@EnableBatchProcessing
public class MyBatchConfig{

  //Your jobRepository and job configuration goes here.

  @Bean
  public ItemProcessor myItemProcessor(MyFeignClient myFeignClient) {
    return (item) -> myFeignClient.postItem(item);
  }

  @Bean
  public RequestInterceptor oauth2BatchRequestInterceptor(OAuth2ClientContext oauth2ClientContext) {
    //This is where we grab the access_token
    //And set is on the feign RequestTemplate
    return (template) -> template.header(HttpHeaders.AUTHORIZATION,
      String.format("%s %s",
        oauth2ClientContext.getAccessToken().getTokenType(),
        oauth2ClientContext.getAccessToken().getValue()
      )
    );
  }
}

Hystrix isolation strategy

Now we set the default isolation strategy of hystrix to SEMAPHORE. Otherwise we will get an error: Method threw 'org.springframework.beans.factory.BeanCreationException' exception.... Scope 'session' is not active for the current thread;

//Prevent hystrix from running (feign) in isolation strategy THREAD. See https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.strategy hystrix.command.default.execution.isolation.strategy: SEMAPHORE

shadow-left