diff --git a/authenticationhandler/tokenmanager.go b/authenticationhandler/tokenmanager.go index 3cd4cd8..0b45e44 100644 --- a/authenticationhandler/tokenmanager.go +++ b/authenticationhandler/tokenmanager.go @@ -13,12 +13,25 @@ import ( // CheckAndRefreshAuthToken checks the token's validity and refreshes it if necessary. // It returns true if the token is valid post any required operations and false with an error otherwise. func (h *AuthTokenHandler) CheckAndRefreshAuthToken(apiHandler apihandler.APIHandler, httpClient *http.Client, clientCredentials ClientCredentials, tokenRefreshBufferPeriod time.Duration) (bool, error) { - if !h.isTokenValid(tokenRefreshBufferPeriod) { + const maxConsecutiveRefreshAttempts = 10 + refreshAttempts := 0 + + for !h.isTokenValid(tokenRefreshBufferPeriod) { h.Logger.Debug("Token found to be invalid or close to expiry, handling token acquisition or refresh.") if err := h.obtainNewToken(apiHandler, httpClient, clientCredentials); err != nil { h.Logger.Error("Failed to obtain new token", zap.Error(err)) return false, err } + + refreshAttempts++ + if refreshAttempts >= maxConsecutiveRefreshAttempts { + return false, fmt.Errorf( + "exceeded maximum consecutive token refresh attempts (%d): access token lifetime (%s) is likely too short compared to the buffer period (%s) configured for token refresh", + maxConsecutiveRefreshAttempts, + h.Expires.Sub(time.Now()).String(), // Access token lifetime + tokenRefreshBufferPeriod.String(), // Configured buffer period + ) + } } if err := h.refreshTokenIfNeeded(apiHandler, httpClient, clientCredentials, tokenRefreshBufferPeriod); err != nil {