Using Antiforgery with Ajax or AngularJs

I installed Microsoft.AspNetCore.Antiforgery my asp.net core.net framework application, add to configuration services

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();
}

I want to use it in the controller and do the following:

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

But I don’t know how to put the key in sight.

+4
source share
1 answer

I suppose you would like Antiforgery to work with Ajax scripts. The following is an example:

In Startup.cs:

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

Filter for creating anti-corrosion token cookies:

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 });
    }
}

Filter Usage:

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

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Product product)
    {
+4
source

Source: https://habr.com/ru/post/1650274/


All Articles