In my Sever Program.cs
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
builder.Services.AddAntiforgery();
app.UseRouting();
app.UseAntiforgery(); // Added this line
app.MapControllers();
///
///
app.Run();
When the client initialized for the first time or make the first API call (GET) to the server the cookies(antiforgery token) is never set why ?
To get around When the app first start I make an API call (GET) that set the cookie manually.
var tokenSet = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokenSet.RequestToken!,
new CookieOptions { HttpOnly = false });
Surprisingly, this now set the “XSRF-TOKEN” cookies along with default “.AspNetCore.Antiforgery._F6fq8lpsLA” but when I make a second POST API request the server always throws Bad Request.
Looks like the antiforgery is not set up properly. Can I please get some guidance on what I am missing. I am using HTTPS for my localhost.
thanks
The antiforgery token should be set when the app load and on each subsequent call the antiforgey token should automatically be attached in the the request header as cookies. The server should validate it with success if it was generated from the server other throw errors
Harry lyod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.