From 76c3088c3a930e5a09b158a5a0ee76cfd2cbe506 Mon Sep 17 00:00:00 2001 From: Roman Mager Date: Thu, 29 Aug 2024 10:27:25 +0300 Subject: [PATCH] Implement token caching --- .../java/com/ypm/service/TokenService.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/ypm/service/TokenService.java b/src/main/java/com/ypm/service/TokenService.java index 2712deb..5e50cdb 100644 --- a/src/main/java/com/ypm/service/TokenService.java +++ b/src/main/java/com/ypm/service/TokenService.java @@ -6,11 +6,16 @@ import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.stereotype.Service; +import java.time.Instant; + @Service public class TokenService { private final OAuth2AuthorizedClientService authorizedClientService; + private String cachedToken; + private Instant expiresAt; + public TokenService(OAuth2AuthorizedClientService authorizedClientService) { this.authorizedClientService = authorizedClientService; } @@ -20,12 +25,23 @@ public String getToken(OAuth2AuthorizedClient authClient) { } public String getToken() { - var authentication = SecurityContextHolder.getContext().getAuthentication(); - var oauthToken = (OAuth2AuthenticationToken) authentication; + if (isTokenExpired()) refreshToken(); + + return cachedToken; + } + + private boolean isTokenExpired() { + return cachedToken == null || Instant.now().isAfter(expiresAt); + } + + private void refreshToken() { + var oauthToken = (OAuth2AuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); var clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId(); var principalName = oauthToken.getPrincipal().getName(); var client = authorizedClientService.loadAuthorizedClient(clientRegistrationId, principalName); - return client.getAccessToken().getTokenValue(); + var accessToken = client.getAccessToken(); + cachedToken = accessToken.getTokenValue(); + expiresAt = accessToken.getExpiresAt(); } }