I have a .net core 2.* API with an Angular 6.* application which I am trying to protect against XSRF attacks.

When logging in, we get an auth token, then we make another call to get a XSRF token.

On the client side we have a HTTP interceptor which appends the token to the header of any subsequent requests made to the API.

The API code looks to be correct and I can see that the response header contains a the XSRF token however, when ever a subsequent request is made to the API Request.Headers["X-XSRF-TOKEN"] exists but it is empty.

Can anyone advise me on where I may have gone wrong?

I have been following this example: https://www.blinkingcaret.com/2018/11/29/asp-net-core-web-api-antiforgery/

API Controller

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

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

UI Service method.


      getAntiForgeryToken(): any {
        return this.http.get(`${this.baseURL}/antiforgery`).pipe(map(x => {
          return true;
        }));
      }

UI http interceptor.


    export class AddCsrfHeaderInterceptorService implements HttpInterceptor {
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            let requestToken = this.getCookieValue('XSRF-REQUEST-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 '';
        }
    }

0 Answers