TransWikia.com

XSRF-TOKEN not added to cookies by Angular (Client side) when .NET core API returns a response with an XSRF-TOKEN

Stack Overflow Asked by Amit Singh Rawat on January 11, 2021

I am using Angular10 and .NET core 2.2. I have configured Startup.cs to return a response with an XSRF-TOKEN. The backend is returning it but Angular doesn’t pass it on to the browser’s cookies.

Reference Microsoft doc https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-3.1#javascript-ajax-and-spas

Api returning XSRF-TOKEN with cookies

Server-side code

  // on ConfigureServices
     services.AddAntiforgery(options =>
        {
            options.HeaderName = "X-XSRF-TOKEN";
        });

// on Configure

app.Use(next => context =>
        {
            string path = context.Request.Path.Value;
            if (path != null && path.ToLower().Contains("/api"))
            {
                var tokens = antiforgery.GetAndStoreTokens(context);

                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                new CookieOptions() { HttpOnly = false });
            }

            return next(context);
        });

One Answer

In my case, Angular does not add XSRF-TOKEN cookies because I am using a different domain for client and API.

To resolve this problem as per @David comment I have to add withCredentials: true to my request

Ex:

this._http.get<Array<string>>(`${environment.config.auth.BASE_API_URL}/Product/GetFeature`, { headers, withCredentials: true});

If you are using single a same domain hosting for Client Angular and Server (in my case asp.net core) Then you do not need to add any configuration on client-side only in case you default cookies name should be "XSRF-TOKEN" and header name should be "X-XSRF-TOKEN".

Answered by Amit Singh Rawat on January 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP