Cross-project AntiForgeryToken validation doesn't work within the same solution's sub-projects

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 : ]

Answer №1

Make sure to set a consistent ApplicationDiscriminator value for all applications in your solution:

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

This identifier distinguishes this application from others on the same machine. It is included in protected data generated by the system to separate multiple logical applications sharing the same key material.

If different applications need to share protected data, they must use the same discriminator value.

Answer №2

Encountering the same issue today - dealing with Ajax requests moving between various .NET Framework IIS applications operating within the identical domain.

I stumbled upon this insightful blog post that provided me with the answer to my dilemma: in Application_Start located in Global.asax.cs for each application, configuring AntiForgeryConfig.CookieName to a consistent fixed value.

Otherwise, distinct cookies were being utilized by each application to store validation tokens.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to initiate a new animation from the current position?

Here is my custom box: <div class="customBox"></div> It features a unique animation: .customBox{ animation:right 5s; animation-fill-mode:forwards; padding:50px; width:0px; height:0px; display:block; background-color:bla ...

Failure to submit form in Bootstrap modal

Can someone please help me troubleshoot why the form in the Bootstrap modal is not submitting? This is the HTML code for the modal (sidebar.php) <!-- Beginning of Joel's modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dia ...

When making a variable call outside of a subscriber function, the returned value is 'undefined'

I find myself in a situation where I have to assign a value to a variable inside a subscriber function in Angular. The issue is that the variable returns 'undefined' when called outside of the Subscribe function. Here's what I'm encount ...

Prevent the div from moving beyond the boundaries of its container while anim

After experimenting with a javascript image panner that I put together from various code snippets, I have decided to switch to a simpler approach. However, I need some guidance on a few things. Below is the code for the left and right buttons: <div id ...

Advancement of a grunt chore within a digital platform

After constructing an app with grunt, I am now in the process of developing a web interface using node and angular to interact with this app. One feature I have implemented is a button that triggers a grunt task using childProcess in NodeJS: child_process ...

What is the best approach to configure Nuxt.js to recognize both `/` and `/index.html` URLs?

Currently, I have set up my Nuxt.js in default mode with universal and history router configurations. After running nuxt generate, the generated website includes an index.html file in the dist folder. This means that when the website is published, it can ...

Issue with Datepicker validation in Angular 5 and Angular Material

I have implemented the most recent version of Angular and Angular Material. I am facing an issue with a datepicker where the validation requirements are not being met as expected. The documentation states that the required attribute should work by default, ...

Tips on displaying dynamic content on a single page with AngularJS 1.6

Just getting started with Angular and looking for a way to display dynamic content from a JSON file using AngularJS 1.6? Here's an example to help you out. News.json { "Articles": [ { "Title": "News 1", ...

After pressing the button to access the sidebar, all I see is a plain white screen

I've been diligently working on a school project, but I'm encountering some issues with the Sidebar button in the top left corner. Whenever I click on the button, it opens up to display a blank white page. Can anyone provide me with some assistan ...

Comparing JSON objects using Javascript and AngularJS

In the page I'm working on, there are several input fields where users can enter data such as text boxes and dropdowns. When a user fills in the data and clicks SAVE, certain checks and manipulations need to be done before the actual saving process st ...

Implement an AJAX function to prompt a save dialog before initiating the download process

I'm currently programming an embedded device in C with a web server. One of the tasks I am working on is downloading files from this device. I need to download several files at once, so I've set up an AJAX request that uses a POST method and send ...

A guide to querying JSON data in a backend database with JavaScript

My backend JSON DB is hosted on http://localhost:3000/user and contains the following data: db.json { "user": [ { "id": 1, "name": "Stephen", "profile": "[Unsplash URL Placehol ...

Each keystroke causes TextField to lose focus

When using an MUI textfield inside a Dialog, I noticed that with each keystroke, the entire dialog is re-rendered and the focus is lost on the textField. However, I observed that each new character I add remains persistent. Here is the dialog where the te ...

Achieving Thread Safety in C# StreamWriter: A Guide

What is the most effective approach to develop a thread-safe program for writing double values to a file when the function that saves the values using a StreamWriter is being called by multiple threads? How can this be achieved in the best way? Code excer ...

Using Node.js: Mimicking Keystrokes on the Server Side (Similar to a Macro)

I am currently working on a node.js script that is designed to replicate the functionality of sending keypresses, such as the up arrow or the "a" button. My ultimate goal is to create a clone of the popular game Twitch Plays Pokemon. Essentially, whenever ...

Creating unique error messages for handling JSON requests

Recently, I've been exploring API development using Rails. My main focus right now is ensuring that the correct error messages are displayed based on the incoming request's errors. Currently, I have a straightforward setup: def create @comp ...

Unable to create selected buttons in Vue.js

I'm having trouble creating buttons that can select all options when clicking on either size or color. The buttons aren't showing up at all. Can someone help me identify the issue? I've attempted various solutions but none seem to work. Any ...

Tips for creating a personalized callback within a user function using JavaScript

Utilizing callbacks is a common practice when working with third-party libraries like jQuery. However, I have encountered a situation where I need to implement my own callback function. Consider the following snippet from my current code: // Get All Rates ...

Transmitting Base64 image data from an Objective-C application to a MVC .Net C# server

I am facing an issue with uploading a Base64 image string from iOS (using NSData+Base64) to MVC .Net. The upload process goes smoothly, however, I encounter an exception when trying to convert the string back to an Image. The exception is thrown at this li ...

Issue with pagination and filtering in Smart-table.js

Presently, my focus is on developing functionality for Smart-table.js, which requires the following features: Retrieve JSON data from a web service Create a table with pagination and filtering capabilities Implement filters for individual columns or globa ...