In my project, I implemented an HTTP interceptor that manages access token refreshing.
If a user's access token expires and the request receives a 401 error, this function is designed to handle the situation by refreshing the token and re-executing the request with the updated access token.
Below is how the function is called:
return next.handle(request).pipe(catchError((error) => {
if (error instanceof HttpErrorResponse && error.status === 401) {
return this.handle401Error(request, next);
} else {
return throwError(error);
}
}));
Here is the implementation of handle401Error method:
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 have followed an article to build this interceptor. The token refreshing process works smoothly except for the line:
return next.handle(this.addToken(request, token.access_token));
This line is supposed to resend the request using the newly obtained valid token but somehow it doesn't trigger.