I have to refresh a token, I use an interceptor to do it but it doesn't seem to work. My function is called but the token isn't refreshed when the API returns the HTTP code 401.
The function of the service
public getToken(): string {
this.token = localStorage.getItem(TOKEN_KEY);
return this.token;
}
Here I post the token I want to refresh
refreshToken() {
console.log(this.token);
return this.http.post<any>(environment.apiBaseUrl + 'refresh', this.token, httpOptions);
}
The interceptor
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
let authReq = req;
const token = this.tokenService.getToken();
if (token) {
authReq = req.clone({
headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token),
});
}
return next.handle(authReq).catch((err: any) => {
console.log(err);
if (err instanceof HttpErrorResponse) {
console.log(err.status);
console.log(err.statusText);
if (err.status === 401) {
this.tokenService.refreshToken();
}
}
return throwError(err);
});
}
}