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"));
        })
    );
}

New contributor

Gustavo Starace is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

It seems like your customInterceptor is mostly set up correctly, but there might be a few reasons why you’re getting a 401 error in your Angular frontend:

Token Synchronization Issue: There might be an issue where the interceptor tries to use the old token even after getting the new one.
Interceptor Chaining Issue: If multiple interceptors are registered, they may not handle the 401 error correctly, causing the token refresh to not propagate properly.
API Request Timing: The token refresh might not have completed before the new request is made.
Angular’s HttpInterceptorFn Syntax: If you are using Angular 16+ with the HttpInterceptorFn function type, ensure the setup is correctly implemented.

tried this code :

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

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

    const token = authService.getAuthToken();
    let cloneRequest = req;

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

    return next(cloneRequest).pipe(
        catchError((error) => {
            if (error.status === 401) {
                // Token is expired or invalid, try refreshing the token
                return authService.refreshToken().pipe(
                    switchMap((res) => {
                        // Store new access token
                        localStorage.setItem('authToken', res.accessToken);

                        // Clone the request with new token and resend it
                        const newReq = req.clone({
                            setHeaders: {
                                Authorization: `Bearer ${res.accessToken}`
                            }
                        });

                        // Continue the request with the new token
                        return next(newReq);
                    }),
                    catchError((refreshErr) => {
                        // Refresh token failed, handle logout or other error
                        console.log("Error refreshing the token:", refreshErr);
                        authService.logout(); // Redirect to login or handle logout
                        return throwError(() => new Error('Session expired, please log in again'));
                    })
                );
            } else {
                // For any other errors
                return throwError(() => error);
            }
        })
    );
};

In authService :

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

    if (!refreshToken) {
        throw new Error('Refresh token missing');
    }
    
    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"));
        })
    );
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật