angularazure-ad-msalmsal.jsmsal-angular

How to redirect a user when the access token expires in MSAL for Angular?


I want to make sure that the user of a Single Page Application gets redirected back to the login page when the access token expires.

As far as I understand MSAL automatically refreshes the access token after expiration. But it does so only when the token expires AND the user makes a new HTTP request.

Is it possible to listen to an MSAL event which fires as soon as the token expires (without the need of further user interaction)?

If getting the token fails, what does MSAL do? Is there a possibility to hook into this event?

I already tried to test this, but my msalBroadcastService.msalSubject$ subscription did not fire any events when the token expired and I could not simulate a failure of getting the token.

I am using MSAL for Angular 13 with RxJS7.


Solution

  • I finally found what seems to me as the proper way.

    Below subscription listens to every HTTP request and emits events e.g. acquireTokenStart or acquireTokenSuccess. If the AccessToken expires or is wrong/deleted, it automatically uses the RefreshToken to get a new AccessToken from the Network. If both tokens are wrong or deleted, acquireTokenFailure gets emited. This can be used to, e.g. redirect or logout the user.

     this.msalBroadcastService.msalSubject$.subscribe({
          next: (msalSubject) => {
            if (msalSubject.eventType === 'msal:acquireTokenFailure') {
              // Do something
            }
          },
        });
    

    Above code is inside ngOnInit. Don't forget to import the MsalBroadcastService and inject it into the constructor.