angularlogoutangular-httpclient-interceptors

Angular Logout Interceptor Not Working Properly


I want the user to be logged out of my application when the token is expired, but it's encountering some problems to the condition I set.

logout.interceptor.ts

export class LogoutInterceptor implements HttpInterceptor {

    constructor(private authService: AuthService) {
    }

    intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        return next.handle(request).pipe(
            catchError((error: HttpErrorResponse) => {
                if (error.status == 401 && error.error.error === 'Token expired') {
                    this.authService.logout();
                }
                console.log(error.status);
                console.log(error.error.error);
                return throwError(error);
            })
        );
    }
}


The results logged on the console are the results I want to see but the condition is not working at all.

I tried handling this in the home.component.ts file and the logic works fine there.

home.component.ts

export class HomeComponent implements OnInit {
    homeData!: any

    constructor(private homeService: HomeService, private toastr: ToastrService, private authService: AuthService) {
    }

    ngOnInit() {
        this.getAll();
    }

    getAll() {
        this.homeService.getAll().subscribe({
            next: (res: any) => {
                this.homeData = res;
                console.log(this.homeData)
            },
            error: (error) => {
                if (error.status === 401 && error.error.error === "Token has expired") {
                    this.toastr.error(error.error.error, error.statusText)
                    console.log("Error On Home Component", error);
                    return this.authService.logout();
                }
                this.toastr.error(error.error.error, error.statusText)
                console.log("Error On Home Component", error);
            }
        })
    }

}


And here is the app.module.ts

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {HTTP_INTERCEPTORS, HttpClientModule} from "@angular/common/http";
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AuthInterceptor} from "./services/auth.interceptor";
import {ToastrModule} from 'ngx-toastr';
import {LogoutInterceptor} from "./services/logout.interceptor";

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        BrowserAnimationsModule,
        ToastrModule.forRoot()
    ],
    providers: [
        {provide: HTTP_INTERCEPTORS, useClass: LogoutInterceptor, multi: true},
        {provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

Interceptor If Condition Not Working Properly

Interceptor isn't logging out users out of the app even if the token has already expired


Solution

  • It appears that you have two HTTP interceptors in your Angular application: AuthInterceptor and LogoutInterceptor. The AuthInterceptor is likely handling authentication-related tasks, while the LogoutInterceptor is supposed to handle logging out when a specific condition is met.

    In your LogoutInterceptor, you're checking for:

    if (error.status == 401 && error.error.error === 'Token expired') {
        this.authService.logout();
    }
    

    But in your HomeComponent, you're checking for:

    if (error.status === 401 && error.error.error === "Token has expired") {
        // ...
    }
    

    The error message in the interceptor is "Token expired," while in the component, it's "Token has expired." These messages should match for the interceptor to work correctly.

    To fix this issue, ensure that the error messages in both the interceptor and the component match. You can update one of them to match the other. For example, you can change the interceptor to:

    if (error.status == 401 && error.error.error === 'Token has expired') {
        this.authService.logout();
    }
    

    when a 401 status code with the correct error message is encountered during an HTTP request interceptor works as expected.