Angular HTTP 拦截器自定义预检

Angular HTTP interceptor custom preflight

我正在编写一个与后端 API 通信的应用程序,需要在每个请求上设置 XSRF-TOKEN header。我已经通过以下 HTTP 拦截器实现了这一点:

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
  const modifiedReq = request.clone({
    headers: request.headers.set('X-XSRF-TOKEN', this.cookieService.get('XSRF-TOKEN')),
  });

  return next.handle(modifiedReq);
}

现在我需要处理 XSRF-TOKEN cookie 尚未设置的情况。在这种情况下,我将需要对我发送的请求进行预检,请求发送到后端 API 上的特定 /csrf 端点,这将 return 一个 Set-Cookie header 设置 XSRF-TOKEN.

作为一个快速而肮脏的测试(没有重构以删除重复代码)我试过这个:

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
  if (!this.cookieService.check('XSRF-TOKEN')) {
    this.apiService.csrf().subscribe(() => {
      const modifiedReq = request.clone({
        headers: request.headers.set('X-XSRF-TOKEN', this.cookieService.get('XSRF-TOKEN')),
      });

      return next.handle(modifiedReq);
    });
  }

  const modifiedReq = request.clone({
    headers: request.headers.set('X-XSRF-TOKEN', this.cookieService.get('XSRF-TOKEN')),
  });

  return next.handle(modifiedReq);
}

但这显然会导致对 /csrf 端点的请求无限循环,因为拦截器中的每个 HTTP 请求都会被自身拦截...

我怎样才能实现我在这里的目标?

只让 /csrf 的请求完成而不拦截它:

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {

  if (request.url === '/csrf') {
    return next.handle(request);
  }

  if (!this.cookieService.check('XSRF-TOKEN')) {
    this.apiService.csrf().subscribe(() => {
      const modifiedReq = request.clone({
        headers: request.headers.set('X-XSRF-TOKEN', this.cookieService.get('XSRF-TOKEN')),
      });

      return next.handle(modifiedReq);
    });
  }

  const modifiedReq = request.clone({
    headers: request.headers.set('X-XSRF-TOKEN', this.cookieService.get('XSRF-TOKEN')),
  });

  return next.handle(modifiedReq);
}