Angular2 ASP.NET Core防伪令牌 [英] Angular2 ASP.NET Core AntiForgeryToken
问题描述
我有一个 Angular2 应用.它在 ASP.NET 5(核心)中运行.
它将Http调用到正常工作的控制器.
但是现在我需要建立跨站点脚本投影.
如何在每个Http请求上生成一个新令牌,然后在Angular2应用中执行AntiForgeryToken检查?
注意:我在Angular中的数据表单不是从MVC视图生成的,而是完全用Angular2编写的,并且仅调用Web服务.
我所看到的所有示例都已过时,无法使用/无法完全使用.
如何在表单为纯Angular的ASP.NET 5中针对 Angular2 集成AntiForgeryToken检查?
谢谢.
自定义操作过滤器不是必需的.都可以在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);
});
(...)
}
然后,您需要在控制器中使用的任何地方都需要[ValidateAntiForgeryToken]装饰器,以强制提供令牌.
作为参考,我在这里找到了此解决方案- AspNet反伪造Github第29期./p>
I have an Angular2 app. It is running within ASP.NET 5 (Core).
It makes Http calls to the controller which is working fine.
But now I need to establish Cross Site Scripting projection.
How do I generate a new token on each Http request and then subsequently perform the AntiForgeryToken check in Angular2 apps?
Note: My data forms in Angular are not produced from an MVC view but entirely written in Angular2 and call web services only.
All the examples I have seen are out dated and do not work / do not work fully.
How do I integrate AntiForgeryToken checks in Angular2 against ASP.NET 5 where forms are pure Angular?
Thanks.
A custom action filter is not necessary. It can all be wired up in 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);
});
(...)
}
Then all you need in your controllers is the [ValidateAntiForgeryToken] decorator wherever you want to enforce that a token is provided.
For reference, I found this solution here - AspNet AntiForgery Github Issue 29.
这篇关于Angular2 ASP.NET Core防伪令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!