我正在使用Angular 8,并使用JWT身份验证。我正在尝试使用拦截器实现令牌刷新逻辑。但是我发现的问题是:
我不确定可以采取什么措施来避免此失败错误。我的拦截器代码如下:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
return next.handle(request).pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
if (error.status === 401 && error.headers.has("Token-Expired")) {
return this.handleUnauthorized(request, next);
}
else {
return throwError(error);
}
})
);
}
handleUnauthorized (request: HttpRequest<any>, next: HttpHandler): Observable<any> {
alert("Refresh error");
this.authenticationService.refreshuser()
.subscribe(
result => {
return next.handle(this.injectToken(request));
},
error=>{
this.authenticationService.logout();
return throwError('');
});
return null;
}
injectToken(request: HttpRequest<any>) {
const token = this.authenticationService.getJwtToken();
return request.clone({
setHeaders: {
'Authorization': `Bearer ${token}`
}
});
}