简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM