The required anti-forgery cookie “__RequestVerificationToken” is not present

It almost sounds as if things are working as expected. The way the anti forgery helper @Html.AntiForgeryToken() works is by injecting a hidden form field named __RequestVerificationToken into the page AND it also sets a cookie into the browser. When the form is posted back the two are compared and if they don’t match or … Read more

Web API and ValidateAntiForgeryToken

You could implement such authorization attribute: [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class ValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter { public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { try { AntiForgery.Validate(); } catch { actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, RequestMessage = actionContext.ControllerContext.Request }; return FromResult(actionContext.Response); } return continuation(); … Read more

How can I supply an AntiForgeryToken when posting JSON data using $.ajax?

You don’t need the ValidationHttpRequestWrapper solution since MVC 4. According to this link. Put the token in the headers. Create a filter. Put the attribute on your method. Here is my solution: var token = $(‘input[name=”__RequestVerificationToken”]’).val(); var headers = {}; headers[‘__RequestVerificationToken’] = token; $.ajax({ type: ‘POST’, url: ‘/MyTestMethod’, contentType: ‘application/json; charset=utf-8’, headers: headers, data: JSON.stringify({ … Read more

jQuery Ajax calls and the Html.AntiForgeryToken()

I use a simple js function like this AddAntiForgeryToken = function(data) { data.__RequestVerificationToken = $(‘#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]’).val(); return data; }; Since every form on a page will have the same value for the token, just put something like this in your top-most master page <%– used for ajax in AddAntiForgeryToken() –%> <form id=”__AjaxAntiForgeryForm” action=”#” method=”post”><%= Html.AntiForgeryToken()%></form> … Read more