Problems implementing ValidatingAntiForgeryToken attribute for Web API with MVC 4 RC

You could try reading from the headers: var headers = actionContext.Request.Headers; var cookie = headers .GetCookies() .Select(c => c[AntiForgeryConfig.CookieName]) .FirstOrDefault(); var rvt = headers.GetValues(“__RequestVerificationToken”).FirstOrDefault(); AntiForgery.Validate(cookie != null ? cookie.Value : null, rvt); Note: GetCookies is an extension method that exists in the class HttpRequestHeadersExtensions which is part of System.Net.Http.Formatting.dll. It will most likely exist in … Read more

Using MVC3’s AntiForgeryToken in HTTP GET to avoid Javascript CSRF vulnerability

The Asp.net MVC AntiForgeryToken won’t work through HTTP GET, because it relies on cookies which rely on HTTP POST (it uses the “Double Submit Cookies” technique described in the OWASP XSRF Prevention Cheat Sheet). You can also additionally protect the cookies sent to the client by setting the as httponly, so they cannot be spoofed … 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