角度拦截器,处理HTTP错误并重试重试、角度、错误、拦截器

2023-09-03 14:39:09 作者:青春惊慌失措

我有一个基本的JWT系统和一个拦截器,它可以检查请求是否由于未经授权而失败。

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

如果请求失败,则我希望在调用this._authService.authenticate();之后重新发送请求。它将重新进行身份验证,因为错误处理会迫使它重新进行身份验证,但随后它不会召回导致应用程序失败的请求,直到我刷新浏览器。

如何解除360错误的拦截

如何让我的警卫再次尝试该请求?

我也尝试使用retryWhen,但得到相同/相似的结果。

推荐答案

在重新对会话进行身份验证后,在HTTp处理程序上调用.Next。理想情况下,您应该从您的身份验证方法返回一个身份验证令牌,然后可以将该令牌追加到请求auth标头上。

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>> {
      return next.handle(req)
            .pipe(
                catchError((error: HttpErrorResponse) => {
                  if (error.status === 401 || error.status === 403) {
                    return this._authService.authenticate()
                      .pipe(
                        mergeMap((token) => next.handle(req.clone({
                                    headers: req.headers.set(AUTH_TOKEN_NAME_HERE, token)
                                })))
                      );
                  }

                    return throwError(error);
                })
            );
  }
}