简体   繁体   中英

How to handle expiring refresh tokens in spring boot rest template client

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.

This is easily done with a ClientHttpRequestInterceptor in which you can replace a requests header if eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM