Search code examples
c#asp.net-corecsrfantiforgerytoken

How do I use ValidateAntiForgeryToken in an HTTP GET request in ASP.NET Core?


Normally you use ValidateAntiForgeryToken with HttpPost, like this:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ...

I want to use ValidateAntiForgeryToken without HttpPost so that I can pass the token in as a URL parameter. How can I do this? Will it just work without HttpPost, and if so, what's the name of the parameter?


Solution

  • With ASP.NET Core 3.1 things seem to be a lot easier.

    All you have to do is pass a "RequestVerificationToken" header in the AJAX-call:

    let token = $('input[name="__RequestVerificationToken"]').val();
    let headers = { "RequestVerificationToken": token };
    $.ajax({ ..., type: 'GET', headers: headers, ... });
    

    For POST-calls, the token can be passed via the object in the body (or the FormData) as a "__RequestVerificationToken" field:

    let postData["__RequestVerificationToken"] = token;
    $.ajax({ ..., type: 'POST', data: postData, ... });
    

    The method in the controller may be defined as follows:

    [ValidateAntiForgeryToken]
    public IActionResult GetNotifications()
    {
        var notifications = _notificationService.GetNotifications();
        return Json(notifications);
    }
    

    Make sure the AntiforgeryOptions.HeaderName and AntiforgeryOptions.FormFieldName are not modified, otherwise change the names above with the respective values.