0

I have a react application authenticating with Azure AD using react-aad-msal library. The below code is working fine. But when the access token expires getAccessToken method automatically fetches the new access token and keeps the application going. But instead, I have a requirement to ask user to reauthenticate when the access token expires and if the user is Idle for the entire duration. Is there a way to do it?

  const apiAuthenticationParameters = {
    scopes: [config.appScope],
    forceRefresh: true,
  };

  const getAccessToken = () => {
    return AuthProvider.getAccessToken(apiAuthenticationParameters);
  };
PNDev
  • 472
  • 3
  • 16

1 Answers1

0

It seems no direct method to check the token if it is about to expire. You could refer to this similar issue with middleware.

const checkTokenExpirationMiddleware = store => next => action => {
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (jwtDecode(token).exp < Date.now() / 1000) {
    next(action);
    localStorage.clear();
  }
  next(action);
};

The default lifetime of access token is 1 hour, see here. You could call logout function after the time.

Pamela Peng
  • 4,095
  • 1
  • 2
  • 8
  • But this approach will logout the active user as well when the token expires. But I need to logout only if the User is idle. I missed to mention in my question, I have updated the question – PNDev Dec 21 '20 at 09:31
  • You could add a judgment on whether the user is idle with [`react-idle-timer`](https://www.npmjs.com/package/react-idle-timer). Logout in this event `handleOnIdle (event) { console.log('user is idle', event) console.log('last active', this.idleTimer.getLastActiveTime()) }`. – Pamela Peng Dec 21 '20 at 09:44