【发布时间】:2018-06-27 20:59:17
【问题描述】:
我正在使用 Ionic 3 和 Angular 5。
我在实现一个 HTTP 拦截器时遇到问题,该拦截器会在我的令牌即将到期时刷新它并使用新令牌发送下一个请求。问题是它在发出请求之前没有等待刷新令牌更新。我该如何解决这个问题?
身份验证服务
refreshToken(token?: string) {
return this.http.get(`${this.API_URL}/refresh`)
.pipe(catchError(this.handleServerError));
}
令牌拦截器
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// If the next request is to my refresh endpoint allow it through
if (URL == `${this.globals.APIURL}/refresh`) {
return request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Accept': 'application/json',
}
});
}
// Else check if token is expiring soon and refresh it and send the new token in the request
else {
const expirationLeft = this.authService.getTokenExpiration();
if (token && expirationLeft < (this.offsetSeconds * 1000) && !this.isUpdating) {
this.isUpdating = true;
try {
this.authService.refreshToken(token)
.subscribe(data =>
{
token = data.token;
this.authService.storeToken(token);
this.authService.authenticationNotifier().next(true);
const clone = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Accept': 'application/json',
}
});
this.isUpdating = false;
return next.handle(clone);
},
(err) =>
{
this.authService.logout();
this.isUpdating = false;
});
}
catch (e) {
}
}
return request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Accept': 'application/json',
}
});
}
【问题讨论】:
标签: angular ionic-framework ionic3