I am trying to implement token interceptor in my Angular front end, but I have one issue with my current implementation.
My interceptor look like this:
intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
if (request.headers.get("No-Auth") === "True") {
return next.handle(request);
}
return next.handle(request).pipe(
catchError(error => {
if (error instanceof HttpErrorResponse && error.status === 401) {
this.handle404Error(request, next);
} else {
return throwError(error);
}
})
);
}
And handle404Error function:
handle404Error(request: HttpRequest<any>, next: HttpHandler) {
if (!this.isRefreshing) {
this.isRefreshing = true;
this.refreshTokenSubject.next(null);
return this.authService.refreshToken().subscribe(
(res: any) => {
if (Boolean(res) === true) {
this.isRefreshing = false;
this.refreshTokenSubject.next(res);
return next.handle(request);
} else {
return this.authService.logout();
}
},
err => {
return this.authService.logout();
},
() => {
this.isRefreshing = false;
}
);
} else {
return this.refreshTokenSubject.pipe(
filter(res => res != null),
take(1),
switchMap(() => {
return next.handle(request);
})
);
}
}
When I make and API call and server return 404, my interceptor will make a call to /token endpoint to obtain new JWT.
Note that I am storing JWT in session object on server (in memory) and on client I have only sessionID and refresh token as HttpOnly cookies.
The problem is, when I make an API call and JWT is not valid, it will set new JWT, but it doesnt send previous request again. (I have to press button twice to get data after JWT expires).
Do you have any idea, how to implement this logic?
Thanks for you help.