skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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!


  2. I agree with @juunas, you can make use of acquireTokenSilent generates the new access token using the refresh token.

    • It attempts to generate a silent token request by using the acquireTokenSilent method.
    • The method first checks the browser storage cache to see if a valid, non-expired access token exists and returns it.
    • If no access token is found, or the found access token is expired, it attempts to use the refresh token to request a new access token.

    Hence you can make use of below code to use acquireTokenSilent:

    const account = publicClientApplication.getAllAccounts()[0];
    
    const accessTokenRequest = {
      scopes: ["user.read"],
      account: account,
    };
    
    publicClientApplication
      .acquireTokenSilent(accessTokenRequest)
      .then(function (accessTokenResponse) {
        let accessToken = accessTokenResponse.accessToken;
        callApi(accessToken);
      })
      .catch(function (error) {
        if (error instanceof InteractionRequiredAuthError) {
          publicClientApplication
            .acquireTokenPopup(accessTokenRequest)
            .then(function (accessTokenResponse) {
              let accessToken = accessTokenResponse.accessToken;
              callApi(accessToken);
            })
            .catch(function (error) {
              console.log(error);
            });
        }
        console.log(error);
      });
    
    • If the refresh token has expired (after 24 hours), the library opens a hidden iframe to silently request a new authorization code.
    • This code is exchanged for fresh access and refresh tokens using the active session with Microsoft Entra ID (if available).

    Otherwise, you can also increase the token lifetime policy and assign it to the application

    Reference:

    Acquire a token to call a web API (single-page apps) – Microsoft identity platform | Microsoft

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search