I have searched a lot but i don't find how to implement the AutoValidateAntiforgeryToken.
I'm creating an Angular 6 spa with TypeScript, connecting to an endpoint .NET Core 2.1
In ConfigureServices added
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
before AddMvc() added in Configure
app.Use(next => context =>
{
string path = context.Request.Path.Value;
if (string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) || string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase))
{
// We can send the request token as a JavaScript-readable cookie,
// and Angular will use it by default.
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
}
return next(context);
});
The Angular documentation is not clear, if i understood well i should read a cookie named X-XSRF-TOKEN and transmit back in the http call as header: but i try to read this cookie in angular (using ngx-cookie-service, with a code as this.cookieSvc.get("X-XSRF-TOKEN")) this cookie is empty.
If someone could help, thanks.
For your issue, check points below to understand your issue better.
XSRF-TOKEN
as cookie name
and X-XSRF-TOKEN
as header Name
for XSRF
.To correspond to Angular
, Asp.Net Core
work with this convention just like you done.
Configure your app to provide a token in a cookie called XSRF-TOKEN
Configure the antiforgery service to look for a header named X-XSRF-TOKEN.
So, if you want to get AntiforgeryToken
from Angular site, try query cookies by XSRF-TOKEN
.