Search code examples
asp.netmodel-view-controllercsrfantiforgerytoken

ASP.NET MVC anti-forgery token (CSRF) not working


I'm trying to imlement the CSRF token into my code, so far without luck. I've figured there are three steps:

My code for the form to be sent:

@using (Html.BeginForm("Manage", "Account"))
{
    @Html.AntiForgeryToken()
}

In my controller view I have written:

public class HomeController : Controller
    {
    [HttpPost]
    [ValidateAntiForgeryToken] 

public ActionResult Index()
    {

        return View("Table");
    } 
    etc...
    }

and my ajax call:

$.ajax({
            type: "POST",
            url: "../Home/" + sFunction,
            contentType: "application/json; charset=utf-8",
            processData: false,
            dataType: "json",
            headers: { "__RequestVerificationToken": 
            $('input[name=__RequestVerificationToken]').val() },
            data: data === null ? null : JSON.stringify(data),

etc.

What am I missing? why is it not working? Thanks


Solution

  • [ValidateAntiForgeryToken] needs to decorate your form post method. Not your index GET method. In this case...

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Manage(YourViewModel model)
    {
        //do your logic
    
        return View(//whatever route & model)
    }
    

    and in your js you add this to your data object.

    let form = //get your form control here
    let data = $(form).serialize();//form is your form control
    data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
    
    $.ajax({
            type: "POST",
            url: //controller/action,
            contentType: "application/x-www-form-urlencoded",
            processData: false,
            dataType: "json",
            data: JSON.stringify(data),
            //etc....
    });