3

I'm working on integrating a third party API in my spring boot application.

How the third party API authentication works:

  1. After initial authorisation, I'm provided with refresh token and access token that expires after a given time
  2. After the access token expires I use the refresh token to get a new access token AND a new refresh token

With the current access token I can make calls to the API.

Is there a way to seamlessly handle such case using RestTemplate?

I've tried handling this case manually, so if I got 401 back from the API I sent a refresh token request, rewrote the keys I got back and retried the request, not really sure how to handle storing the api keys in case I need to restart the server.

mgol
  • 31
  • 1
  • 1
  • 2
  • When is access token getting expired? Ie is it something like after 30 mins of inactivity or exactly at after 30 mins? The provider should be able to answer/specified in the contract. Base from that you should consistently know when to send the "re-authentication" – Jayr May 27 '19 at 15:18
  • How about [Oauth2RestTemplate](https://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/client/OAuth2RestTemplate.html) ? Take a look – Barath May 27 '19 at 16:27

1 Answers1

12

This is easily done with a ClientHttpRequestInterceptor in which you can replace a requests header if e.g. a 401 occured:

@Override
public ClientHttpResponse intercept(
  HttpRequest request, 
  byte[] body, 
  ClientHttpRequestExecution execution) throws IOException {

    ClientHttpResponse response = execution.execute(request, body);
    if(response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
       request.getHeaders().replace("Auth-Header", getNewToken());
       return execution.execute(request, body);
    }
    return response;
}

See here for further guidance.

roookeee
  • 1,710
  • 13
  • 24
  • how would you put all of it inside the IOC ? – Tiago Medici May 23 '22 at 13:54
  • I don't understand your question. You are probably providing your `RestTemplate` as a `@Bean` which can autowire your custom `ClientHttpRequestInterceptor` in its factory method – roookeee May 24 '22 at 08:37
  • my RestTemplate must be a bean since i m using apiclient generated from swagger plugin, at that moment i must inject the interceptor in the resttemplate after spring boot app has been initialized, i got to solve it – Tiago Medici May 24 '22 at 08:47
  • This solution causes thread locks on the restTemplate, seems like a bad solution. (Only difference is that I add the token before the first request also) – sadxd May 27 '22 at 07:22
  • Thread get locked because response before UNAUTHARIZATION check is still there I assume. Need to close response inside if check: response.close(); – Yernar Arystanov Jul 20 '22 at 13:37