Skip to content

Commit

Permalink
Forms 1078 token refresh failure (bcgov#1329)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
jasonchung1871 and vijaivir authored May 15, 2024
1 parent 54de902 commit 7bcb9cd
Showing 1 changed file with 33 additions and 7 deletions.
40 changes: 33 additions & 7 deletions app/frontend/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};
Expand Down

0 comments on commit 7bcb9cd

Please sign in to comment.