我有一个 Angular2 应用程序。它在 ASP.NET 5 (Core) 中运行。
它对工作正常的 Controller 进行 Http 调用。
但现在我需要建立跨站点脚本投影。
如何在每个 Http 请求上生成一个新 token ,然后在 Angular2 应用程序中执行 AntiForgeryToken 检查?
注意:我在 Angular 中的数据表单不是从 MVC View 生成的,而是完全用 Angular2 编写的,并且仅调用 Web 服务。
我看到的所有示例都已过时并且无法正常工作/无法完全正常工作。
我如何在 Angular2 中将 AntiForgeryToken 检查集成到表单为纯 Angular 的 ASP.NET 5 中?
谢谢。
最佳答案
自定义操作过滤器不是必需的。它可以全部连接到 Startup.cs 中。
using Microsoft.AspNetCore.Antiforgery;
(...)
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
(...)
}
public void Configure(IApplicationBuilder app, IAntiforgery antiforgery)
{
app.Use(next => context =>
{
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 });
}
return next(context);
});
(...)
}
然后,在您的 Controller 中,您只需要 [ValidateAntiForgeryToken] 装饰器即可强制提供 token 。
作为引用,我在这里找到了这个解决方案 - AspNet AntiForgery Github Issue 29 .
关于web-services - Angular2 ASP.NET Core AntiForgeryToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36295167/