When my JWT authentication token expires (verified by the backend), I need to call a refresh token API and resend the last failed request due to the expired token.
I have an Interceptor in place, but I must update the authentication header before sending the request and wait for the refreshToken
call.
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { shouldRetry } = this;
return next.handle(request).pipe(
retryWhen(genericRetryStrategy({
shouldRetry
})),
catchError(err => {
// If status is 401, token is invalid so refresh it
if (err.status === 401) {
this.auth.refreshToken().subscribe(
(apiResult: SessionTokenResponse) => {
this.auth.saveToken(apiResult.token);
},
error => this.auth.logout()
);
request = request.clone({headers: request.headers.set('Authorization', 'Bearer ' + this.auth.getSessionToken)});
return next.handle(request);
}
const error = err.error.message || err.statusText;
return throwError(error);
}),
)
}
Is this the correct approach to resend the call? How can I ensure the completion of refreshToken
? Thank you
EDIT: I have updated the code with a revised version that appears to be functioning correctly. Currently testing it out.
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { shouldRetry } = this;
return next.handle(request).pipe(
retryWhen(genericRetryStrategy({
shouldRetry
})),
catchError(err => {
// If status is 401, token is invalid so refresh it
if (err.status === 401) {
this.auth.refreshToken().subscribe(
(apiResult: SessionTokenResponse) => {
this.auth.saveToken(apiResult.token);
request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + apiResult.token) });
next.handle(request).subscribe();
},
err => this.auth.logout()
);
}else{
const error = err.error.message || err.statusText;
return throwError(error);
}
}),
)
}