4

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.

MikhailRatner
  • 452
  • 6
  • 13
  • Have you also tried to subscribe to ```this.msalBroadcastService.inProgress$``` ? – Charlie V Jun 17 '22 at 13:37
  • 1
    Why not using a class which implements HttpInterceptor. When you intercept an httpError like 401, you redirect to the specific page. – Matthieu Jun 17 '22 at 14:26
  • 1
    I did a crappy workaround that refreshes the tokens every 45 min if idle. But I am hoping you find a better solution in this thread. Following. – Joshua Fellers Jun 20 '22 at 11:53
  • @CharlieV yes I did, but it completes the subscription right after the login, thus, it does not listen to further events. Or is there something specific you would like to point out? – MikhailRatner Jun 21 '22 at 06:12
  • @Matthieu I do have an HttpInterceptor... do you know the error status code / message which comes from the backend when getting the token fails? – MikhailRatner Jun 21 '22 at 06:16
  • 1
    I think it should be a 401 or a 403. It depends what your api check on the request. But you can put a verification on the both. – Matthieu Jun 21 '22 at 13:33
  • @JoshuaFellers I finally found a better solution. What do you think? – MikhailRatner Jun 23 '22 at 11:40

1 Answers1

1

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.

MikhailRatner
  • 452
  • 6
  • 13