After refreshing the token, the existing request to the original API replace with the /refersh-token API so I need to double check on button for data

82 views Asked by At

When the token gets expired next: HttpHandler handle the request that comes from the server when it go inside the refershToken Subscribe method it goes to the header that I defined above the next.handle(request) and again comes to the next.handle(request) so my previous request go to the client and didn't update with the refresh token and now my existing request is /refersh-token. so after updating the token I need to double check on the button for the records or reload the page for the records.


// add authorization header with jwt token if available

refreshToken is API configuration in authenticationService class

refreshToken() {
  return this.http.get<CommonResponse>(`${environment.apiUrl}/refresh-token`);
}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

const currentUser = this.authenticationService.currentUserValue;
if (currentUser?.token && 
  !environment.publicURLS.includes(request.url.replace(environment.apiUrl, "")) 
  && !this.router.url.includes("https://www.google.com/inputtools/request")) {
  request = request.clone({
    setHeaders: {
      Authorization: `Bearer ${currentUser.token}`,
    },
  });
}


return next.handle(request).pipe(tap((data: any) => {
      if (data.body?.body) {
        if (data.body.body.isTokenExpired) {
          this.authenticationService.refreshToken().pipe(map((res) => {
            return res;
          })).subscribe(res => {
            if (res?.body && !res?.isError && res?.body?.token) {
              const currentUser = this.authenticationService.currentUserValue;
              if (currentUser) {
                currentUser.token = res.body.token;
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                this.authenticationService.currentUserValueSubject.next(currentUser);
                const retryRequest = request.clone({
                  setHeaders: {
                    Authorization: 'Bearer ' + currentUser.token,
                  },
                });
                next.handle(retryRequest);
              }
            }
          }
          );
        }
        if (data.body.body.isTokenInvalid) {
          this.authenticationService.logout();
        }
      }
    }
    ));
  }
0

There are 0 answers