AntiForgeryToken doesn't validate across sub project of same solution

1

I am implementing CSRF in MVC application. I created custom attribute to validate token as my inputs are json encode and call by Ajax. It works fine in the same project but when any button or link call url across different project in same solution then it doesn't validate the token. E.g logoff is in main page and calling different project's controller in the same solution. It keep on throwing "The anti-forgery cookie token and form field token do not match." I have machine key already set up in the web configs. Can you guys please help me figure it out this issue.

Thank you

logoff method - main.js file in 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 : ]

javascript
c#
json
ajax
model-view-controller
asked on Stack Overflow Sep 9, 2019 by HNP • edited Sep 9, 2019 by Sergey Kudriavtsev

2 Answers

1

Try configuring all applications in your solution to specify the same ApplicationDiscriminator value:

var dataProtectionBuilder = services.AddDataProtection(configure =>
{
    configure.ApplicationDiscriminator = "SharedAppName";
});

An identifier that uniquely discriminates this application from all other applications on the machine. The discriminator value is implicitly included in all protected payloads generated by the data protection system to isolate multiple logical applications that all happen to be using the same key material.

If two different applications need to share protected payloads, they should ensure that this property is set to the same value across both applications.

answered on Stack Overflow Sep 9, 2019 by Jan Doubek • edited Jun 20, 2020 by Community
0

I ran into the same problem today. Ajax requests going between different .NET Framework IIS apps running on the same domain.

This blog post gave me the solution to my problem: in Application_Start of Global.asax.cs on each app, setting AntiForgeryConfig.CookieName to the same fixed value.

Without this, each app used different cookies for saving validation tokens.

answered on Stack Overflow Jun 19, 2020 by FTWinston

User contributions licensed under CC BY-SA 3.0