I have separate frontend project in Angular 2 without using MVC and backend project is Web Api (Asp.Net Core) both are hosted on different domain. I implemented AntiForgery token functionality but it is not working.
Frontend project (UI)- http://localhost:8080/
Backend project (Web Api) - http://localhost:4823/
I am able to receive and send XSRF-Token
cookie in every request but api gives 400 Bad Request
error.
I followed this link-
Angular2 ASP.NET Core AntiForgeryToken
Startup.cs
-
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
services.AddCors(options =>
{
options.AddPolicy("AllowAllCorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IAntiforgery antiforgery)
{
app.Use(async (context, next) =>
{
if (context.Request.Path == "/")
{
//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 });
}
}
}
Controller code-
[EnableCors("AllowAllCorsPolicy")]
[ValidateAntiForgeryToken]
[Produces("application/json")]
[Route("api/Aoi")]
public class AoiController : Controller
{
...
}
Angular code-
let options = new RequestOptions({ headers: headers, withCredentials:true });
this._http.post(this.aoiUrl, bodydata, options)
.map((res: Response) => {
let data = res.json();
return data;
})