我在 Angular 2 中有单独的前端项目而不使用 MVC,后端项目是 Web Api (Asp.Net Core),它们都托管在不同的域上。我实现了 AntiForgery 令牌功能,但它不起作用。
前端项目(UI)-http://localhost:8080/
后端项目(Web 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 });
}
}
}
控制器代码-
[EnableCors("AllowAllCorsPolicy")]
[ValidateAntiForgeryToken]
[Produces("application/json")]
[Route("api/Aoi")]
public class AoiController : Controller
{
...
}
角码——
let options = new RequestOptions({ headers: headers, withCredentials:true });
this._http.post(this.aoiUrl, bodydata, options)
.map((res: Response) => {
let data = res.json();
return data;
})