我有一个基本的JWT系统,还有一个Interceptor,用于检查请求是否由于未经授权而失败。
import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {AuthService} from '../services/auth.service';
import {catchError, retryWhen} from 'rxjs/operators';
@Injectable()
export class AuthenticationErrorInterceptor implements HttpInterceptor {
private readonly _authService: AuthService;
constructor(authService: AuthService) {
this._authService = authService;
}
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({headers: req.headers});
return next.handle(authReq)
.pipe(
catchError((err) => this._handleAuthError(err)),
retry(3)
);
}
private _handleAuthError(error: HttpErrorResponse): Observable<any> {
if (error.status === 401 || error.status === 403) {
return this._authService.authenticate();
}
return throwError(error);
}
}
如果请求确实失败,那么我想在致电[C0]之后重新发送请求。由于错误处理的原因,它将强制重新进行身份验证,但是它不会重新调用导致应用程序失败的请求,直到我刷新浏览器。
我如何让我的警卫再次尝试该请求?
我也尝试过使用this._authService.authenticate();
,但得到的结果相同/相似。
在重新认证会话后,请在HTTP处理程序上调用.next。理想情况下,您应该从您的authenticate方法返回一个身份验证令牌,然后可以将其附加到请求auth标头中。
retryWhen