Thursday, 8 April 2021

angular http interceptor not calling request again after token refresh

I have a http interceptor in my project, it handles the refreshing of the access token.
When a user's access token expires the request will get a 401 error, in that case, this function should handle everything, refreshing the token and calling the request again, with the new access token.

Here is the calling of the function:

return next.handle(request).pipe(catchError((error) => {
  if (error instanceof HttpErrorResponse && error.status === 401) {
    return this.handle401Error(request, next);
  } else {
    return throwError(error);
  }
}));

And the handle401:

  handle401Error(request: HttpRequest<any>, next: HttpHandler): any {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);

      this.auth.refreshAccessToken().then((token: Token) => {
        this.isRefreshing = false;
        this.refreshTokenSubject.next(token.access_token);
        return next.handle(this.addToken(request, token.access_token));
      });
    } else {
      return this.refreshTokenSubject.pipe(
          filter((token) => token !== null),
          take(1),
          switchMap((token) => {
            return next.handle(this.addToken(request, token));
          }));
    }
  }

I created the interceptor from an article, which should work fine, the token refreshing works like a charm, but the

return next.handle(this.addToken(request, token.access_token));

Which should call the request again with the now valid token just doesn't call it.



from angular http interceptor not calling request again after token refresh

No comments:

Post a Comment