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
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 theacquireTokenSilent
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.I call
acquireTokenSilent
in my interval token refresh as the docs advise against pre-emptively authenticating the user usingacquireTokenRedirect
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!
I agree with @juunas, you can make use of
acquireTokenSilent
generates the new access token using the refresh token.acquireTokenSilent
method.Hence you can make use of below code to use
acquireTokenSilent
: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