From 7bcb9cd5f0fe69eb505d876f3c1d60034518ecd9 Mon Sep 17 00:00:00 2001 From: jasonchung1871 <101672465+jasonchung1871@users.noreply.github.com> Date: Tue, 14 May 2024 23:45:04 -0700 Subject: [PATCH] Forms 1078 token refresh failure (#1329) * Added intervals for updating token Created a function for updating the token. This function is executed when the keycloak detects the token as expired, as well as every normal 60 seconds, as well as whenever there is an update token failure. Upon failure of updating the token, it will create an interval to keep updating the token, upon success, it will clear that interval. * Update main.js added token clearing if there was an error when updating the token * Update main.js removed deprecated success, error promises. replaced it with a then and catch promise. --------- Co-authored-by: Vijaivir Dhaliwal <91633223+vijaivir@users.noreply.github.com> --- app/frontend/src/main.js | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/app/frontend/src/main.js b/app/frontend/src/main.js index 8fca5980e..7734a0f8a 100755 --- a/app/frontend/src/main.js +++ b/app/frontend/src/main.js @@ -227,21 +227,47 @@ function loadKeycloak(config) { authStore.ready = true; typeof options.onReady === 'function' && options.onReady(); }; + + let updateTokenInterval; + // The expired token is also used for general update token failures + // i.e., network disconnection + let expiredTokenInterval; + + function updateToken(seconds) { + keycloak + .updateToken(seconds) + .then((refreshed) => { + if (refreshed) { + if (expiredTokenInterval) clearInterval(expiredTokenInterval); + } else { + // token is still valid + } + }) + .catch(() => { + // We're failing to update the token + }); + } + keycloak.onAuthSuccess = () => { // Check token validity every 10 seconds (10 000 ms) and, if necessary, update the token. // Refresh token if it's valid for less then 60 seconds - const updateTokenInterval = setInterval( - () => - keycloak.updateToken(60).catch(() => { - keycloak.clearToken(); - }), - 10000 - ); + updateTokenInterval = setInterval(async () => { + updateToken(60); + }, 10000); authStore.logoutFn = () => { clearInterval(updateTokenInterval); + clearInterval(expiredTokenInterval); authStore.updateKeycloak(keycloak, false); }; }; + keycloak.onTokenExpired = () => { + if (!expiredTokenInterval) { + expiredTokenInterval = setInterval(() => { + updateToken(60); + }, 10000); + } + updateToken(60); + }; keycloak.onAuthRefreshSuccess = () => { authStore.updateKeycloak(keycloak, true); };