I have Api calls which uses OAUTH token this auth tokens are specific to different user and have a expiry period of 24 hrs. But sometimes even if the expire time is not up when the api call is made it returns invalid token. Is their a way in which I can retry the api call one more time in the above scenerio by getting the new user access token. The user access token is also got by making an api call. I am using Java reactive webclient with spring boot.
public Mono<Abc> create(Long customerId, Abc abc) {
return profileRepo.findByCustomerId(customerId)
.map(profile -> refreshTokens(customerId)
.flatMap(tokens ->
client.create(token,getProfile(customerId))))
.orElseThrow(ResourceNotFoundException::new);
}
public Mono<Token> refreshTokens(final Long customerId) {
Token token = service.findByCustomerId(customerId);
if (LocalDateTime.now().isAfter(token.getExpiryTime())) {
newToken = client.refresh(token);
}
return newToken;
}
Api call for token refresh and create
public Mono<Token> refresh(final Token token) {
return client.post()
.uri(OAUTH_TOKEN_PATH)
.header(AUTHORIZATION, basicAuth()) // The master token of the service provider
.body(forRefreshToken(new RefreshToken(token.getRefreshToken())))
.retrieve()
.onStatus(HttpStatus::is4xxClientError, response -> response.bodyToMono(String.class)
.flatMap(error -> Mono.error(new ClientResponseException(response.statusCode().value(),response.statusCode(),error))))
.onStatus(HttpStatus::is5xxServerError, response -> response.bodyToMono(String.class)
.flatMap(error -> Mono.error(new ClientResponseException(response.statusCode().value(),response.statusCode(),error))))
.bodyToMono(Token.class);
}
public Mono<Abc> create(final Token token, Profile pro) {
return client.post()
.uri(PATH_V2)
.header(AUTHORIZATION, token.bearer())
.contentType(APPLICATION_JSON)
.body(fromObject(pro))
.retrieve()
.onStatus(HttpStatus::is4xxClientError, response -> response.bodyToMono(String.class)
.flatMap(error -> Mono.error(new ClientResponseException(response.statusCode().value(),response.statusCode(),error))))
.onStatus(HttpStatus::is5xxServerError, response -> response.bodyToMono(String.class)
.flatMap(error -> Mono.error(new ClientResponseException(response.statusCode().value(),response.statusCode(),error))))
.bodyToMono(Abc.class);
}
Thanks in advance, Sameekshya