Skip to content

Commit

Permalink
Implement token caching
Browse files Browse the repository at this point in the history
  • Loading branch information
leingenm committed Aug 29, 2024
1 parent 7e53a31 commit 76c3088
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/main/java/com/ypm/service/TokenService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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();
}
}

0 comments on commit 76c3088

Please sign in to comment.