ASP.NET MVC Anti Forgery Tokens

25 Views Asked by At

I have asp.net MVC application in which bootstrap, telerik Kendo UI (for MVC) have also used. The controllers have [ValidateAntiForgeryToken] attribute and in razor pages (.cshtml) following implemenation is used:

@using (Ajax.BeginForm("AddComments", "Comments", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "closeCommentsModal" }))
{
    @Html.AntiForgeryToken()
    -----
    -----
    <Comment - Bootstrap model is used and here is footer example>
<div class="modal-footer buttons">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
}

The save button does a ajax call as below

function saveField(field, value) {
    $.ajax({
        type: "POST",
        url: $("#SAVEFIELD").val(),
        data: { session: $("#SESSION").val(), field: field, value: value },
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "JSON"
    });
}

This calls the MVC controller method which is implemented as below:

[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult SaveSessionField(Guid session, string field, string value)

The entire functionality works but recently we are upgrading to bootstrap 5.0 and now we have to modify jquery function to pass anti-frogery token to get response from MVC controller. The modified jquery function is as below:

function saveField(field, value) {
    var token = $("[name='__RequestVerificationToken']").val();
    $.ajax({
        type: "POST",
        url: $("#SAVEFIELD").val(),
        data: { session: $("#SESSION").val(), field: field, value: value, '__RequestVerificationToken': token },
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "JSON"
    });
}

My question is why bootstrap 5 upgrade require to pass anti frogery token separately in jquery function ? Why it was working in older version of bootstrap without passing anti frogery token ? Do we need to upgrade ajax version also to avoid passing token separately in jquery function ? I have lots of jquery functions so I don't want to modify all functions to pass token value. Do we have a global way to manage token in ASP.NET MVC project so that we can avoid changing javascript functions ?

0

There are 0 best solutions below