使用Antiforgery与Ajax或AngularJs

zer*_*ing 4 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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

但不知道如何将密钥放入视图中.

Kir*_*lla 6

我想你希望Antiforgery能够使用Ajax场景.以下是一个例子:

在Startup.cs中:

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

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

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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

过滤器的用法:

    [HttpGet]
    [GenerateAntiforgeryTokenCookieForAjax]
    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Product product)
    {
Run Code Online (Sandbox Code Playgroud)

  • 并且不要忘记添加"使用Microsoft.Extensions.DependencyInjection",否则通用的GetService扩展将不可用. (4认同)