azuremsal.jsmicrosoft-entra-id

How to Listen for MSAL Access Token Expiration


Is there a way to listen for the access token's expiration? It seems silly to me that Microsoft will set the expiration time between 60-90 minutes arbitrarily. Perhaps I don't understand the motivation behind it?

I would like to respond to an event, if at all possible, rather than setting a recurring 60 minute timer to refresh the user's access token.


Solution

  • TL;DR To answer the question: no, you cannot listen for when tokens/sessions expire with MSAL. Other methods such as acquireTokenSilent or event callbacks are recommended to handle it.


    Found great answers here, but not exactly answering the question of the post.

    I do not use acquireTokenSilent upon every API request because if it were to fail then the user (and by extension malicious actors) will know what actions are secure and worth exploiting. So I separate the acquireTokenSilent call from the API call.

    For pages that are only visible when the user is authenticated, I essentially send a preflight request before navigation to the page to ensure the user is granted access to the page and call acquireTokenSilent if need be (there's more to it, but unrelated to the post). If this process fails then I respond to the following events to correct the user's authenticated state in the application: LOGIN_SUCCESS, ACQUIRE_TOKEN_SUCCESS, and ACQUIRE_TOKEN_FAILURE.

    instance.enableAccountStorageEvents();
    instance.addEventCallback((message) => {
        if ((message.eventType === EventType.LOGIN_SUCCESS || message.eventType === EventType.ACQUIRE_TOKEN_SUCCESS) && message.payload.account) {
            // Set the authenticated state
        } else if (message.eventType === EventType.ACQUIRE_TOKEN_FAILURE && message.interactionType === InteractionType.Silent) {
            // Clear the authenticated state
            instance.acquireTokenRedirect(loginRequest);
        }
    });
    

    I call acquireTokenSilent in my interval token refresh as the docs advise against pre-emptively authenticating the user using acquireTokenRedirect here.

    As I've stated in the comments, my application is implemented with the SPA platform in Entra and cannot adjust the access token's lifetime per the discussion here.

    I should clarify, nothing is inherently wrong with what I've implemented (otherwise I would have posted some code), but seeing that none of the documentation or discussions suggest expiration events are emitted from MSAL, I'm led to believe that it's more of a security risk if they were. And I'm not stating this is the answer others should follow, but it works for my application per the requirements given to me.

    Hope this helps!