We are doing some migration from old .NET framework to .NET Core and I need to add antiforgery token handling.
In my ASP.NET Core 8 Web API, I configured and added a middleware:
public const string ANTIFORGEY_TOKEN_HEADER_NAME = "__RequestVerificationToken";
public static void ConfigureAntiforgeryToken(this WebApplicationBuilder builder)
{
builder.Services.AddAntiforgery(options =>
{
// Set Cookie properties using CookieBuilder properties
options.FormFieldName = "AntiforgeryToken";
options.HeaderName = GeneralAppConstants.ANTIFORGEY_TOKEN_HEADER_NAME;
options.SuppressXFrameOptionsHeader = false;
});
}
public class AntiforgeryTokenMiddleware(IAntiforgery antiforgery) : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (!HttpMethods.IsPost(context.Request.Method))
{
await next(context);
}
else
{
var executingEnpoint = context.GetEndpoint();
var attributes = executingEnpoint.Metadata.OfType<ValidateJsonAntiForgeryTokenAttribute>();
if (attributes?.Any() ?? false)
{
await antiforgery.ValidateRequestAsync(context);
}
}
}
}
When I hit my endpoint with request where I set the header with:
__RequestVerificationToken: some token
I got the following error
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery cookie “.AspNetCore.Antiforgery.mirJ4ZzQPmw” is not present.
Then I tried to add another middleware that will add a XSRF-TOKEN
cookie:
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var tokenSet = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokenSet.RequestToken!, new CookieOptions { HttpOnly = false });
}
But I get the same error.
I can see in the request header the values:
Set-Cookie: some token
I tried to copy it to the Insomnia and test it, but always the same error.
Thanks