I'm using a interceptor in Angular to refresh token 10 minutes before this expires, but when I called the API to refresh the token, this API is called too many times.
This is my code
constructor(
private store: Store,
private authService: AuthenticationService,
private http: HttpClient
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.store.snapshot().auth.selectedToken;
if (token) {
const decodedToken: any = jwt_decode(token);
//Se verifica que al token le queden 10 minutos o menos para actualizarlo
const expirationTime = 28 * 60 * 1000;
const expirationDate: any = new Date(decodedToken.exp * 1000);
const currentTime = new Date();
const shouldRefreshToken = expirationDate.getTime() - currentTime.getTime() < expirationTime;
if (shouldRefreshToken) {
const url = AppConfig.API_ENDPOINT;
const email = this.store.snapshot().auth.email;
const token = this.store.snapshot().auth.azureToken;
const refresh = this.store.snapshot().auth.refresh;
const user = this.store.snapshot().auth.user;
this.http.post(`${url}/refresh_session`, { email, token, refresh }).subscribe({
next: (res: any) => {
console.log(res);
this.authService.storeSession(res.app_token, email, user, res.azure_token.token, res.azure_token.refresh);
const clonedRequest = request.clone({
setHeaders: {
Authorization: `Bearer ${res.app_token}`
}
});
return next.handle(clonedRequest);
},
error: (err: any) => {/**/}
});
}
}
return next.handle(request);
}
I tried with pipe instead of subscribe but it's not works.