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
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);
});
The difference between the X-CSRF-TOKEN and X-XSRF-TOKEN is that the first uses a plain text value and the latter uses an encrypted value, because cookies in Laravel are always encrypted. If you use the csrf_token() function to supply the token value, you probably want to use the X-CSRF-TOKEN header.
Cross-site request forgery (also known as XSRF or CSRF) is an attack against web-hosted apps whereby a malicious web app can influence the interaction between a client browser and a web app that trusts that browser.
A CSRF token is a secure random token (e.g., synchronizer token or challenge token) that is used to prevent CSRF attacks. The token needs to be unique per user session and should be of large random value to make it difficult to guess. A CSRF secure application assigns a unique CSRF token for every user session.
To fetch a CRSF token, the app must send a request header called X-CSRF-Token with the value fetch in this call. The server generates a token, stores it in the user's session table, and sends the value in the X-CSRF-Token HTTP response header.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With