9

I have to integrate with external service that requires access token to be sent with each requests. Access token has a short expiration time (only a few hours). I've decided to use access token in optimistic way. I'm going to call external service with current token. I case of getting 401 I'm going to refresh the token and call the external API one more time.

I've decided to use ClientHttpRequestInterceptor to implement described retry mechanism.

public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
   ClientHttpResponse response = execution.execute(request, body);
   if(response.getStatusCode() == UNAUTHORIZED) {
       refreshToken();
       updateToken(request);
       response = execution.execute(request, body);
   }
   return response;
}

I have tested it and it works, but is it allowed to call execution.execute() twice? I haven't found any information that it's forbidden, but from the other hand I haven't seen such code as well.

pmajcher
  • 537
  • 6
  • 14
  • I have the same need and I have thought to use an interceptor similar to the one you propose. Has this solution been valid or have you encountered problems? I can not find anything about how to propose this negotiation of tokens – Jose Luque Jun 04 '18 at 08:56

1 Answers1

5

we are doing exactly the same - and having issues. This snippet of code you have there will leak connections as the original response is ignored and not closed properly. My current solution is to explicitly close it and then do the second execution. Seems to work so far but I guess it needs more evaluation.

Witko
  • 53
  • 3