Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

Refresh token before time out Angular

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);
    });
  }
}
question from:https://stackoverflow.com/questions/65921066/refresh-token-before-time-out-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...