Angular 6 - не удается получить AntiforgeryToken в HttpInterceptor - PullRequest
0 голосов
/ 26 октября 2019

У меня есть этот http-перехватчик для обработки токена Antiforgery:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable} from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class AddCsrfHeaderInterceptorService implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      const requestToken = this.getCookieValue('XSRF-TOKEN');
      return next.handle(req.clone({
          headers: req.headers.set('X-XSRF-TOKEN', requestToken)
      }));
  }

  private getCookieValue(cookieName: string) {
      const allCookies = decodeURIComponent(document.cookie).split('; ');
      for (let i = 0; i < allCookies.length; i++) {
          const cookie = allCookies[i];
          if (cookie.startsWith(cookieName + '=')) {
              return cookie.substring(cookieName.length + 1);
          }
      }
      return '';
  }
}

А внутренний код - ASP.NET Core Web Api, как показано ниже:

[ApiController]
    public class AntiForgeryController : ControllerBase
    {
        private IAntiforgery _antiForgery;
        public AntiForgeryController(IAntiforgery antiForgery)
        {
            _antiForgery = antiForgery;
        }

        [Route("api/antiforgery")]
        [AllowAnonymous]
        [HttpGet]
        [IgnoreAntiforgeryToken]
        public IActionResult GenerateAntiForgeryTokens()
        {
            var tokens = _antiForgery.GetAndStoreTokens(HttpContext);
            Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new Microsoft.AspNetCore.Http.CookieOptions
            {
                HttpOnly = false
            });
            return NoContent();
        }
    }

Я пробую этометод приложения Почтальон, и результат: enter image description here

, но когда я запускаю приведенный ниже код, чтобы получить тот же результат, поле cookie документа в http-перехватчике пусто:

this.brandService.getCsrfToken().subscribe(f => {
      this.brandService.incrementVisitors().subscribe(x => {
        console.log(x);
      });
     });

incrementVisitors(): Observable<Statistics> {
    return this.http.get<Statistics>(this.baseUrl + 'publicbrands/IncrementVisit');
  }

  getCsrfToken(): Observable<any> {
    return this.http.get<any>(this.baseUrl + 'antiforgery');
  }
...