I am developing a web API
app running using asp.net core2
and Angular
. The detailed development environment config is here.
I am trying to configure AntiForgeryToken
validation but it keeps failing. I followed the config. here, but I had to modify it as my angular app and asp.net servers are running on two different ports because the front end startup doesn't generate the token. I kick start the backend by calling an API
path (/api/Account/ContactInitialization
) at the app component ngOnInit
which allowed me to generate the token.
The config is shown below,
IServiceCollection
Service:
services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
options.SuppressXFrameOptionsHeader = false;
});
and at IApplicationBuilder Configure
:
app.Use(next => context =>
{
string path = context.Request.Path.Value;
if (
string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) ||
string.Equals(path, "/api/Account/ContactInitialization", 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);
});
asp.net. generates two set of keys,
I decorated my method with [ValidateAntiForgeryToken]
and I included XSRF-TOKEN
cookie content in my header request. yet I keep receiving a 400 (Bad Request)
response after calling the API
! what am I missing here?
Controller Method,
[Authorize]
[ValidateAntiForgeryToken]
[HttpPost]
public IEnumerable<string> AutherizeCookie()
{
return new string[] { "Hello", "Auth Cookie" };
}
my detailed header request looks like below,
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…