I have an application written with ASP.net (v2.2) and Angular8. The C# side (server-side) is just a web-API that exposes functionality to the Angular (client-side) application.
My client-side application is using SSR (server-side rendering) in order to present the application to the users.
I want to activate the anti-forgery mechanism from the ASP.net on my application. The way it should work that on any HTTP request I will attach an anti-forgery cookie and will validate it on my web-api controllers (server side\c#).
I tried to write a middleware that will attach the cookie to the response. It looks like this (base on this):
public class AntiForgeryTokenMiddleware
{
private readonly RequestDelegate _next;
private readonly IAntiforgery _antiforgery;
public AntiForgeryTokenMiddleware(RequestDelegate next, IAntiforgery antiforgery)
{
_next = next;
_antiforgery = antiforgery;
}
public Task Invoke(HttpContext context)
{
if (context.Request.Path.Value.IndexOf("/your api endpoint, e.g. /api", StringComparison.OrdinalIgnoreCase) != -1)
{
var tokens = _antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false, Secure = false });
}
return _next(context);
}
}
But, I found that the middleware is happening only when the page is loaded for the first time. After clicking on a link - I expected that my middleware will be triggered again, but it's not.
For this reason, my AntiForgery cookie is invalid when the webapi is verified it - the URL is changed but the cookie not.
How to solve this issue?