使用Antiforgery与Ajax或AngularJs

时间:2016-08-05 07:51:58

标签: c# asp.net-core

我安装了Microsoft.AspNetCore.Antiforgery我的asp.net核心.net框架应用程序,添加到配置服务

public void ConfigureServices(IServiceCollection services)
{
  // Add framework services.
  services.AddApplicationInsightsTelemetry(Configuration);
  services.AddTransient<ISession, JwtSession>(s => JwtSession.Factory());
  //services.AddCors();
  services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
  services.AddMvc();
}

我想在控制器中使用它并执行如下操作:

    [Route("[action]"), Route("")]
    [HttpGet]
    public IActionResult Index()
    {
      var f = _antiforgery.GetAndStoreTokens(HttpContext);
      return View();
    }

但不知道如何把钥匙放进去看。

1 个答案:

答案 0 :(得分:5)

我想您希望Antiforgery能够使用Ajax方案。以下是一个例子:

在Startup.cs中:

https://

生成防伪令牌cookie的过滤器:

 // Angular's default header name for sending the XSRF token.
 services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

过滤器的用法:

public class GenerateAntiforgeryTokenCookieForAjaxAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext context)
    {
        var antiforgery = context.HttpContext.RequestServices.GetService<IAntiforgery>();

        // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
        var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
        context.HttpContext.Response.Cookies.Append(
            "XSRF-TOKEN",
            tokens.RequestToken,
            new CookieOptions() { HttpOnly = false });
    }
}