const SESSION_JWT_LAST_UPDATED = 'jwtTokenLastUpdated'; const SESSION_JWT_GAP = 'jwtGAP'; let refreshCounter = 0; async function checkJwtRefresh(){ const timeoutMins = 10; let elapsedTimeMinutes = 0; //Check Session Storage to see if we need to refresh our Cookie const lastUpdated = sessionStorage.getItem(SESSION_JWT_LAST_UPDATED); const currentJWT = sessionStorage.getItem(SESSION_JWT_GAP); if(lastUpdated && currentJWT){ elapsedTimeMinutes = (Date.now() - lastUpdated) / 60000; console.log(elapsedTimeMinutes + ' minutes since last refresh.'); if(elapsedTimeMinutes >= timeoutMins){ console.log('Time To Refresh Token. '); refreshCounter++; //TODO:only set this session storage if the getJWTForGAP is successful. sessionStorage.setItem(SESSION_JWT_GAP, await getJWTForGAP()); //window.newJWTValue = await getJWTForGAP(); } } else { console.log('No existing token detected. Fetching Token.'); refreshCounter++; sessionStorage.setItem(SESSION_JWT_GAP, await getJWTForGAP()); //window.newJWTValue = await getJWTForGAP(); } //Refresh every 10-11 minutes for a total of 10 times, which results to about 100 minutes of idle time on the same page. //We don't want to loop indefinitely. Weird SF related bug forces me to use < for less than... //TODO: don't forget to set this value back to 10 before going to UAT and PROD if(refreshCounter < 100){ setTimeout(checkJwtRefresh, 60000); } } async function getJWTForGAP(){ const cookieName = "PD-S-SESSION-ID="; const aimEndpoint = 'https://securest.medavie.bluecross.ca/mga/sps/apiauthsvc?PolicyId=urn:ibm:security:authentication:asf:getjwt'; let aimSessionCookie = document.cookie.split("; ").find((row) => row.startsWith(cookieName)); let jwtGAP = ''; if(!aimSessionCookie){ aimSessionCookie = 'PD-S-SESSION-ID=dUPS+ipjUxDhhaR35844PQ==:1_2_1_e7Wm379Gj2BpSAHTNQbQEjdx-Wa2CbhehhvQpFIOCnE5rBna|'; } const aimHeaders = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Cookie': aimSessionCookie, 'Host': 'securest.medavie.bluecross.ca' }; try{ //Using Fetch API to get the JWT token from AIM;. Only include the following headers. const responseFromWebSeal = await fetch(aimEndpoint,{ method: 'GET', headers: aimHeaders, redirect: 'follow', credentials: 'include' }); if(responseFromWebSeal.ok){ const responseData = await responseFromWebSeal.json(); console.log(responseData); //Check if we got a successful response from webseal if(responseData.data){ jwtGAP = responseData.data.jwt; sessionStorage.setItem(SESSION_JWT_LAST_UPDATED,Date.now()); console.log('Successfully retrieved JWT Token' + responseData.data.jwt); } else if(responseData.error) { console.log('Error from Webseal: ' + responseData.error.message); } else { console.log('Unknown Error from Webseal: ' + responseData); } } } catch (error) { console.log('Fetch call error: ' + error.message); } return jwtGAP; } checkJwtRefresh();