1

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);
    });
  }
}
leri
  • 261
  • 1
  • 3
  • 12

1 Answers1

2

Inside tokenService.refreshToken you need to store the token somewhere in tokenService for it to be picked up by this.tokenService.getToken() in the following request (or retry of you have retry behavior)

Something like:

refreshToken() {
    console.log(this.token);
    this.token = this.http.post<any>(environment.apiBaseUrl + 'refresh', this.token, httpOptions);
  }
Raz Ronen
  • 2,418
  • 2
  • 14
  • 26