[英]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. 我关注了几篇文章,以在Angular上实现JWT身份验证,除了检测到401未经授权之外,其他所有功能似乎都可以正常工作。
I want to redirect the user to login page but I cannot detect the 401 error. 我想将用户重定向到登录页面,但无法检测到401错误。
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 我有
auth.service.ts
,其中包含login()
和jwt.interceptor.ts
getToken()
方法,以及jwt.interceptor.ts
,其中包含
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
. 我必须在
module.app.ts
添加多个拦截器。 Don't forget to add @Injectable()
before export class...
in the interceptor. 不要忘记在拦截器的
export class...
之前添加@Injectable()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.