angularjwtangular2-jwt

Angular Detect 401 Unauthorized Access using JWT


I followed a couple of articles to implement JWT authentication on Angular and seems everything is working except detecting 401 unauthorized.

I want to redirect the user to login page but I cannot detect the 401 error.

I have this class:

export class JwtInterceptor implements HttpInterceptor {

  constructor(public authService: AuthService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        console.log('HTPP REQUEST');
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          this.authService.collectFailedRequest(request);
          console.log('Login boy');
        }
      }
    });
  }
}

But not sure where to use it. I have auth.service.ts which contains login() and getToken() methods and jwt.interceptor.ts which contains


Solution

  • providers: [PagerService, AuthService,
      {
        provide: HTTP_INTERCEPTORS,
        useClass: TokenInterceptor,
        multi: true
      }, {
        provide: HTTP_INTERCEPTORS,
        useClass: JwtInterceptor,
        multi: true
      }
    ]
    

    I have to add multiple interceptors in the module.app.ts. Don't forget to add @Injectable() before export class... in the interceptor.