web-services - Angular2 ASP.NET Core AntiForgeryToken

标签 web-services angular asp.net-core xss

我有一个 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/

相关文章:

java - 我需要学习 Java 中的 Web 服务。它有哪些不同的类型?

java - wsimport/xjc 命令行插件

javascript - Angular Video 对事件发出多个请求

asp.net-core - 无法找到外部组件中的 ViewComponent

c# - 当我更改计算机日期格式并且无法检索日期选择器值时,ASP.NET MVC Core DateTime 表现得很奇怪

php - 处理太多 mysql 连接的最佳实践

java - 如何返回org.springframework.http.ResponseEntity包括数据和文件

Angular2 AOT 编译器不断询问名称

javascript - 解析错误 [{{}}] 或使用清理不安全的网址

logging - 使用 NLog 进行依赖注入(inject)