#handle Refresh token for many http requests

11 messages · Page 1 of 1 (latest)

proud sleet
#

i have built a token interceptor to handle all the http requests including the 401, now my main issue is if i fire like 50 requests (loading a dashboard for historical data and not live, i have one for the live and its done via socket) at the same time and the token is expired, all of these requests will return a 401, and the refresh token will be done a couple of times which breaks some of these requests, my question is how do i handle the refresh token in such a case

#

this is a code sample im using

  private handleHttpErrorResponse(request: HttpRequest< Object >, next: HttpHandler) {
    if (!this.isTokenRefreshing) {
      this.isTokenRefreshing = true;
      localStorage.setItem(environment.storage_keys.tokenRefreshing, JSON.stringify(this.isTokenRefreshing));
      this.tokenSubject.next(null);
      return this.authService.RefreshToken().pipe(
        switchMap((tokenResponse: IResponseRequest < IRefreshTokenResponse >) => {
          if (tokenResponse) {
                this.isTokenRefreshing = false;
                localStorage.setItem(environment.storage_keys.tokenRefreshing, JSON.stringify(this.isTokenRefreshing));
                this.tokenSubject.next(tokenResponse.result.token);
                return next.handle(this.addToken(request, tokenResponse.result.token));
              }
                return throwError('no token found');
            }),
            catchError((err: HttpErrorResponse) => {
                return this.logoutUser();
          })
        );
    } else {
        return this.tokenSubject.pipe(
            filter(token => token != null),
            take(1),
            switchMap(token => {
                return next.handle(this.addToken(request, token));
            })
        );
    }
}
heavy chasm
#

You probably want your call to get a new token to use share()

#
getToken$ = this.authService.RefreshToken().pipe(share())

Then use this.getToken$ instead of this.authService.RefreshToken() in the interceptor error handler

forest bloom
#

Inside HttpInterceptors class check token expire. If token expire you should before send HttpRequest get new token and sign request by new token. Also, check all error in interceptor and use retryWhen.

heavy chasm
#

On top of that, we typically check the expiration of the token client-side, and request a new token about 60seconds before it expires. That way, users never get all kinds of 401 when all u want is to refresh the token for them..

forest bloom
proud sleet
heavy chasm
heavy chasm
#

They go together.