locked
Put field __RequestVerificationToken along with JSON data in ajax script RRS feed

  • Question

  • User-2133486755 posted

    I have an ajax script which calls method with following parameters.

        [HttpPost]
        [Authorize(Roles ="Klient")]
        [ValidateAntiForgeryToken]
        public ActionResult ChangeHouseParticipants(string houseName, List<Participant> participants)
        {
             return View();
        }

    This script presents in that way.

    for (var i = 0; i < list.length; i+=3) {
        	jsonArray.push({ Name: list[i].value, Surname: list[i+1].value, BirthDate: list[i+2].value });
            }
        var data = JSON.stringify({
        	houseName: $('select[name="SelectedHousesParticipants"]').val(),
        	participants: jsonArray,
        });
        $.ajax({
        	type: "POST",
        	url: "/ClientReservations/ChangeHouseParticipants",
        	data: data,
        	headers: {
        		'__RequestVerificationToken': $("[name='__RequestVerificationToken']").val()
        	},
        	contentType: "application/json; charset=utf-8",
        	success: function (response) {
        		$('assignedParticipants').html(response)
        	},
        	}
        });

    I thought that adding field with token into headers section would solve the issuse. But I still got the message that __RequestVerificationToken is not present. Any proposals, How to solve it?

    Saturday, August 26, 2017 11:03 AM

Answers

  • User475983607 posted

    I thought that adding field with token into headers section would solve the issuse. But I still got the message that __RequestVerificationToken is not present. Any proposals, How to solve it?

    The antiforgery framework compares a cookie POST form field.  The framework is not looking for the token in the HTTP header. If you want this functionality then you need write some code.  

    Create a filter attribute that looks for the token in the header and compares that to the cookie.

        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
        public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
        {
            public void OnAuthorization(AuthorizationContext filterContext)
            {
                if (filterContext == null)
                {
                    throw new ArgumentNullException("filterContext");
                }
    
                var httpContext = filterContext.HttpContext;
                var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
                AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
            }
        }

    References

    https://nozzlegear.com/blog/send-and-validate-an-asp-net-antiforgerytoken-as-a-request-header.

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 26, 2017 12:05 PM