1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Angular HTTP Interceptor executing inner http request twice

Discussão em 'Angular' iniciado por mduck, Setembro 30, 2024 às 23:32.

  1. mduck

    mduck Guest

    My application uses a JWT Token to authenticate with the backend. I have an angular Interceptor that catches any errors in an http call. This interceptor checks if the call returns a 401 Unauthorized response and if so, it makes a call to an endpoint to refresh the token and then retries the original call again.

    My issue is that the call to the refreshToken endpoint is being done twice for some reason.

    Here's my interceptor (edited for brevity):

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
    catchError((error: any) => {
    switch (error.status) {
    // unauthorized
    case 401:
    // the token is stored in an NGRX store, so retrieve it first
    return this.userStore.pipe(select(fromUser.getUserAccessToken)).pipe(
    take(1),
    mergeMap(userToken => {
    if (userToken) {
    // token exists but may be invalid, try to refresh
    return this.userService.refreshToken(userToken).pipe(
    switchMap(refreshedToken => {
    if (refreshedToken) {
    ...
    } else {
    // token was not refreshed, delete session
    ...
    }
    })
    );
    }
    })
    );
    }
    })
    );
    }


    return this.userService.refreshToken(userToken) is the statement that gets executed twice (using the same, original token), so the first call to refresh will go through, and the second call will obviously fail since its trying to refresh the same token again, resulting in the user session getting deleted.

    Any ideas why?

    Update: I'm still digging through this. I've put a bunch of breakpoints and console.logs in my code:

    catchError((error: any) => {
    >>>>> console.log('1');
    switch (error.status) {
    case 401:
    return this.userStore.pipe(select(fromUser.getUserAccessToken)).pipe(
    take(1),
    mergeMap(userToken => {
    >>>>> console.log('2');
    if (userToken) {
    return this.userService.refreshToken(userToken).pipe(
    switchMap(refreshedToken => {
    >>>>> console.log('3');


    Console.log #1 and #2 get printed out to the console just once, which means that the http error is only being caught once. But #3 gets printed twice, which I figure means either the call to the refresh endpoint is being made twice, or the observable is returning two values somehow?

    Continue reading...

Compartilhe esta Página