简体   繁体   English

Angular HTTP 拦截器自定义预检

[英]Angular HTTP interceptor custom preflight

I'm writing an application that communicates with a backend API that requires a XSRF-TOKEN header be set on every request.我正在编写一个与后端 API 通信的应用程序,该后端需要在每个请求上设置XSRF-TOKEN header。 I've achieved that with the following HTTP interceptor:我已经通过以下 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);
}

Now I need to handle the case where the XSRF-TOKEN cookie is not yet set.现在我需要处理尚未设置XSRF-TOKEN cookie 的情况。 In this case I will need to preflight the request that I'm sending with one that hits a specific /csrf endpoint on the backend API, which will return a Set-Cookie header to set XSRF-TOKEN .在这种情况下,我需要预检我发送的请求,该请求会命中后端 API 上的特定/csrf端点,这将返回Set-Cookie header 以设置XSRF-TOKEN

As a quick and dirty test (without refactoring to remove duplicate code) I tried this:作为一个快速而肮脏的测试(没有重构以删除重复的代码),我尝试了这个:

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

But this obviously has the consequence of an infinite loop of requests to the /csrf endpoint, as each HTTP request inside the interceptor is intercepted itself...但这显然会导致对/csrf端点的请求无限循环,因为拦截器内的每个 HTTP 请求都会被自己拦截......

How can I achieve what I'm going for here?我怎样才能实现我在这里的目标?

Just let the request to /csrf complete without intercepting it:只需让对/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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM