angularjwtangular-httpclientrefresh-tokenangular-httpclient-interceptors

401 Unauthorized Error during token refresh API call


I can't solve the implementation of refresh tokens, my backend is OK at PostMan works OK, with a curl command it's OK too, I send the header with a refresh token and the backend responses with an object with an accessToken that works ok too, but when I use the frontend the error is a 401! Please help me.!

This is the Interceptor:

export const customInterceptor: HttpInterceptorFn = (req, next) => {
    const excludedRoutes = ['/login']; // Customizable array
    const shouldExclude = excludedRoutes.some(route => req.url.includes(route));
    const authService = inject(AuthService);

    if (shouldExclude) {
        return next(req);
    }

    const token = authService.getAuthToken();
    const cloneRequest = req.clone({
        setHeaders: {
            Authorization: `Bearer ${token}`
        }
    });

    return next(cloneRequest).pipe(
        catchError((error) => {
            if (error.status === 401) {
                console.log("From the interceptor, here is the error: " + error.status);
                return authService.refreshToken().pipe(
                    switchMap((res) => {
                        localStorage.setItem('authToken', res.accessToken);
                        console.log("From the interceptor, the new authToken is: " + res.accessToken);
                        const newReq = req.clone({
                            setHeaders: {
                                Authorization: `Bearer ${res.accessToken}`
                            }
                        });

                        return next(newReq);
                    }),
                    catchError((refreshErr) => {
                        const finalError = new Error(refreshErr);
                        console.log("Error refreshing the token", finalError);
                        authService.logout();
                        return throwError(() => new Error('Session expired, please log in again'));
                    })
                );
            } else {
                // Handle other errors (e.g., network errors)
                return throwError(() => error);
            }
        })
    );
};

This is the service method:

refreshToken() {
    const refreshToken = localStorage.getItem('refreshToken');
    console.log("The refreshToken inside the method is: " + refreshToken);

    if (!refreshToken) {
        throw new Error('Refresh token missing');
    }
    
    console.log("Sending refresh token to backend: " + refreshToken);
    
    return this._httpClient.post<any>(`${this.baseURL}/refresh`, {}, {
        headers: {
            Authorization: `Bearer ${refreshToken}`
        }
    }).pipe(
        catchError((error) => {
            console.error("Refresh token error:", error);
            return throwError(() => new Error("Refresh error"));
        })
    );
}

Solution

  • "You should add path '/refresh' to your excludedRoutes array. Now outdated access token is being added to /refresh request, it may be the reason of 401 – leonmain"

    Commented yesterday

    Solved my problem, thanks for all!!!