zero_coding zero_coding - 3 months ago 59
C# Question

Using Antiforgery with Ajax or AngularJs

I installed Microsoft.AspNetCore.Antiforgery my asp.net core .net framework application, add to the configure 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 a controller and did as follow:

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


But do not know how to put the key into view.

Answer

I suppose you would like Antiforgery to work with Ajax scenarios. Following is an example:

In Startup.cs:

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

A filter to generate antiforgery token 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 });
    }
}

Usage of the filter:

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

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