Currently, I am working on implementing CSRF in an MVC application. In order to validate the token for inputs that are JSON encoded and called via Ajax, I have created a custom attribute. The validation works perfectly within the same project. However, when a button or link from a different project within the same solution triggers a call to a URL, the token validation fails. For example, the logoff action exists on the main page but calls a controller in a different project within the solution. This leads to the error message "The anti-forgery cookie token and form field token do not match." I have already configured the machine key in the web configs. Could anyone offer assistance in resolving this issue?
Thank you
Logoff Method - Main.js file in the main project
A.ajax({
url: config.authenticationUrl + '/Account/LogOff',
method: 'POST',
data: serialisedExtent,
contentType: 'application/json',
headers: {
'__RequestVerificationToken': $('input[name=__RequestVerificationToken]').val()
}
})
Controller Method in Account Controller in Authentication Project
[HttpPost]
[ValidateHeaderAntiForgeryToken]
public async Task<ActionResult> LogOff([ModelBinder(typeof(JsonNetModelBinder))] Exten extent)
{
if (User != null &&
User.Identity != null &&
User.Identity.IsAuthenticated)
}
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"]);
}
Error:
The anti-forgery cookie token and form field token do not match.
[exception : System.Web.Mvc.HttpAntiForgeryException (0x80004005): The anti-forgery cookie token and form field token do not match. at System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken) at System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase httpContext, String cookieToken, String formToken) at ValidateHeaderAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext) in at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.b__0(AsyncCallback asyncCallback, Object asyncState)] [method : ] [caller : ] [context : ]