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
#handle Refresh token for many http requests
11 messages · Page 1 of 1 (latest)
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));
})
);
}
}
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
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.
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..
It can give 401 when connection unstable
yes but what if im doing the the request before 60 seconds and this one occures in between the 50 requests, like when the 30th request fires the 401 from the client-side fires too i will have mixed tokens and this did happen to me once so thats why im asking you for an advice and ill try to add the share and the retrywhen
It can probably give a lot of things when the connection is stable, but yes the point is here in the typical usage. Obviously u still need to account for edge case scenarios
That's why I gave the other solution.
They go together.