Angular Detect 401使用JWT进行未经授权的访问

时间:2018-02-26 16:57:23

标签: angular jwt angular2-jwt

我跟着几篇文章在Angular上实现JWT身份验证,似乎一切正常,除了检测401未经授权。

我想将用户重定向到登录页面,但我无法检测到401错误。

我有这堂课:

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

但不确定在哪里使用它。我的auth.service.ts包含login()getToken()方法,jwt.interceptor.ts包含

1 个答案:

答案 0 :(得分:0)

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.