我在Angular 2中使用独立的前端项目而不使用MVC,而后端项目是Web Api(Asp.Net Core)都托管在不同的域中。我实现了AntiForgery令牌功能,但它不起作用。使用Aps.Net核心在Angular 2和Web Api中实现AntiForgery令牌实现我使用Aps.Net核心
前端项目(UI) -
后端项目(网页API) - http://localhost:4823/
我能接受,并在每个请求发送XSRF-Token
Cookie,但API为400 Bad Request
错误。 我跟着这个链路 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 });
}
}
}
控制器代码 -
角代码 -
let options = new RequestOptions({ headers: headers, withCredentials:true });
this._http.post(this.aoiUrl, bodydata, options)
.map((res: Response) => {
let data = res.json();
return data;
})