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

Using fresh cookies from catchError in HttpIntercopterFn [Angular18]

Discussão em 'Angular' iniciado por Asad Koths, Novembro 8, 2024 às 02:22.

  1. Asad Koths

    Asad Koths Guest

    I have created an interceptor to ensure HttpOnly jwt/refresh tokens are sent with every request. I am attempting to refresh my short lived jwt by catching a 401 error and asking the server for a refresh. It seems to be working though perhaps not as I expect. This is my code:

    export const jwtInterceptor: HttpInterceptorFn = (req, next) => {
    const router: Router = inject(Router);
    const authService: AuthService = inject(AuthService);

    req = req.clone({
    withCredentials: true,
    });

    return next(req).pipe(
    catchError((err: any) => {
    if (err instanceof HttpErrorResponse) {
    // Handle HTTP errors
    if (err.status === 401) {
    // handle unauthorized errors
    console.error('Unauthorized request:', err);
    // retry the request
    authService.refreshToken().subscribe({
    next: () => {
    authService.isRefreshed$.next(true);
    },
    error: () => {
    // Redirect to login page
    authService.logout(true);
    return router.createUrlTree(['/login'], {
    queryParams: { returnUrl: router.url },
    });
    },
    });
    return authService.isRefreshed$.pipe(switchMap(() => next(req)));
    } else {
    // Handle other HTTP error codes
    console.error('HTTP error:', err);
    }
    } else {
    // Handle non-HTTP errors
    console.error('An error occurred:', err);
    }
    // Re-throw the error to propagate it further
    return throwError(() => err);
    })
    );
    };


    When I look at the network calls through developer tools it looks like the calls are made in the order I expect. The cookie is refreshed successfully, but not being used in the retried request. I cannot modify the request with the HttpOnly cookie through TS so I'm unsure of how to proceed.

    The goal is to retry the failed request with the refreshed cookie. In the future I will think about cacheing multiple request and retrying them in a queue.

    Continue reading...

Compartilhe esta Página