How to listen to token expiry using Forgerock's appAuthHelper library

42 Views Asked by At

I am using this library for Forgerock tokens inside a ReactJS application: https://github.com/ForgeRock/appAuthHelper

I re-read the README and the closest thing I can see from that document that listens to getting a token is the tokensAvailableHandler method. So when I call the init method, I make sure to pass in the the tokensAvailableHandler

AppAuthHelper.init({ tokensAvailableHandler: () => console.log('trigger tokensAvailableHandler') });

I can verify that this method is called when the first token is received. However, once the first token gets expired, a new one is generated then given to the ReactJS application but this method tokensAvailableHandler is not being called again.

Is there any other way to listen to new tokens whenever the old one expires (I need to listen to this to trigger some other process flow)?

1

There are 1 best solutions below

0
Carlos Jaime C. De Leon On

The best one I managed to find is listening to the appAuthHelper iframe's message events (which was not mentioned in the README.md) which I found by trawling thru the source code.

The library does use window's postMessage and publishes several types of message: https://github.com/search?q=repo%3AForgeRock%2FappAuthHelper+parent.postMessage&type=code

The one that fit my requirement of being notified once new token is generated after expiry is this message appAuth-tokensAvailable https://github.com/ForgeRock/appAuthHelper/blob/7c9e59f1391ae55fc8413baa04dd7bcdf3853507/appAuthHelperFetchTokens.js#L22

Wherein my code is like this:

window.addEventListener("message", (msg) => {
   if (msg.data.message === 'appAuth-tokensAvailable') {
   // handle the scenario when token expires and gets regenerated
   }
});

In case someone else has a better solution, please share it here