Troubleshooting the Anti-forgery Token Problem with ASP.NET MVC and AngularJS Integration

Hey there!

I've been struggling with a problem for some time now and can't seem to figure it out. I have an ASP.NET MVC project with an added Angular JS project on top of it. I also have a Web API, but that's not important for this issue. The web application itself is driven by the Angular project, which makes calls to the API.

For authentication, I'm using the default system from ASP.NET MVC with the standard Login.cshtml View and AccountController methods for login/logout.

The issue I'm facing is as follows:

When a user logs into the website and then clicks the browser's Back button, they are prompted with the login form again. If they enter their credentials once more, I encounter an HttpAntiForgeryException stating "The provided anti-forgery token was meant for a different claims-based user than the current user."

I've tried solutions like disabling the back button with JavaScript (window.history.forward(1);), but it doesn't work consistently across older browser versions. Reloading the login page doesn't solve the problem either.

Any suggestions?

Thanks in advance!

Update: I've included

AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;
in Application_Start() and added the following code:

public class HandleAntiForgeryError : ActionFilterAttribute, IExceptionFilter {
    #region IExceptionFilter Members

    public void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception as HttpAntiForgeryException;
        if (exception != null)
        {
            var routeValues = new RouteValueDictionary();
            routeValues["controller"] = "Account";
            routeValues["action"] = "Login";
            filterContext.Result = new RedirectToRouteResult(routeValues);
            filterContext.ExceptionHandled = true;
        }
    }

    #endregion }

[HandleAntiForgeryError]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
}

The only remaining issue is that when I click back and try to log in with another user, it fails. It seems to keep me logged in with the previous user. Is there a way to change this behavior so that if I enter new credentials after clicking back, I get logged in with the new user instead?

SOLVED: Turns out, the culprit was this line in my code:

if (User.Identity.IsAuthenticated)
    return RedirectToAction("Index", "App");

This line was causing me to be redirected to the index page with the old credentials after logging in with a different user. Removing it fixed the issue.

Answer №1

Dealing with a similar problem, I successfully resolved it by inserting the following line within the Application_Start() event in the Global.asax file:

AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;

Additionally, remember to include this code snippet in the Application_Error() function:

Exception ex = Server.GetLastError();
            if (ex is HttpAntiForgeryException)
            {
                Response.Clear();
                Server.ClearError(); //ensure exception logging
                Response.Redirect("~/Home/Index", true);
            }

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

When refreshing a JavaScript array of objects, it creates duplicate entries within the array

Currently, I am developing a chat application within a Vue project and experimenting with different features. A fully-featured chat app must have the ability to live-update "seen" states. This means that when one user views the last sent message, the othe ...

Preventing a user from inputting a value below 1 in a number input field within Vue 3

I'm working on implementing a number input field in Vue 3 that restricts the user from entering a value less than 1. Currently, I have set the minimum value to 1 to prevent using the input arrows to go below 1: <input min="1" type="n ...

Retrieve data from a JSON file

I have a JSON file containing various player data, and I need to extract the "Name" field from it. { "player": [ { "Position": "TEST", "Name": "TEST", "Squad_No": "TEST", "Club": "TEST", "Age": "TEST" }, ...

Setting CSS Class Dynamically in AngularJS Runtime

I need to apply a CSS class to the row where the MaxStockLevel is greater than the Balance. I tried using this code: <tbody ng-repeat="i in products | filter:productFilter"> <!--<tr ng-class="{{i.MaxStockLevel > i.Balance ? 'danger&a ...

Unable to properly bind events onto a jQuery object

I have been attempting to attach events to jquery objects (see code snippet below), but I am facing challenges as it is not functioning properly. Can someone provide me with a suggestion or solution? Thank you! var img = thumbnail[0].appendChild(document. ...

The class 'System.Web.HttpInputStream' does not have the serializable attribute applied

I am encountering an issue while attempting to upload a byte[] to Azure blob storage, resulting in the following exception: Error: Type 'System.Web.HttpInputStream' in Assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyTok ...

What is the reason behind receiving a CSS warning stating "Expected color but found '0' " when using Phaser's setText() function?

Here's how I created my text object: statusBarHP.text = game.add.text(0, 0, '', { font:"16px Arial", fill:"#ffffff", stroke:"#000000", strokeThickness:2 }); For the object that holds the text: statusBarHP = game.add.sprite ...

Need help implementing the disableGutters property on MTableToolbar?

I am currently using react material-table and I would like to customize the default toolbar styles by passing the prop disableGutters={true}, similar to how it's done in material-ui toolbar. Below is the code snippet that I have tried: <MaterialTab ...

What is the most effective way to set up HTTPS for handling all connections in Node.js?

In my project to create a stateless authentication system using Double Submit Cookie in Node.js/ExpressJs, I am exploring ways to ensure all connections are made over HTTPS. My goal is to optimize for handling high traffic while also prioritizing security ...

Using Ajax and PHP to store multiple checkbox selections into the database

I currently have 32 checkboxes on my page that I need to track the checked status for. In my JavaScript, I am looping through each checkbox and assigning a value of '1' for checked and '0' for unchecked. // Example for one checkbox if ...

Angular is capable of transforming the date into the format of dd/mm/yyyy

Received date format from the server is as follows: "tranDate":"2015-11-29T18:30:00.000Z" When trying to display the date in the view using the code snippet below, the date appears as - 30/11/2015 (it should be 29/11/2015). <td>{{stmt.tranDate | d ...

Using React Higher Order Components to render multiple sibling nodes independently without a common parent node

Are you looking to create a Higher-order React component that can render multiple sibling nodes, but without the need for a parent node? Currently, I am utilizing React.cloneElement to render children elements with a parent element. const RenderChildren ...

How can Angular JS and HTML5 be used to dynamically create controls?

I have designed a unique project to demonstrate dynamic control creation using angularjs and html5. The project includes an xml file with a set of controls, complete with property and event attributes that can be generated dynamically. Initially, all the ...

add component automatically upon selection

Imagine I have a special <SelectPicker/> element that allows me to choose an option. What I am trying to figure out is how I can include another <SelectPicker/> once I have made a selection. function DynamicComponent() { const [state, setSta ...

When it comes to Redux, is it considered an anti-pattern to pass an event from a presentational component to a container component

As a newcomer to Redux, I am challenging myself to rebuild an old React app using this technology in order to gain proficiency. However, I am facing a significant challenge regarding where to place the logic within the application. My understanding is tha ...

How can data be typically encapsulated within Pinia stores when leveraging the composition API?

Currently, in my Vue 3 application with Pinia, I am interested in leveraging the composition API within my Pinia stores. Take a look at this example store: export const useMyStore = defineStore("my", () => { const currentState = ref(0); return ...

Tips for sending personalized data in an Angular $routeParams object

Is there a proper way to specify custom values in the routeObject when configuring the Angular $routeProvider, and then retrieve them using the $route object that Angular injects? For example: $routeProvider .when('/administration/user/:id' ...

JavaScript Instant Validation: Ensuring Accuracy in Real-Time

I am trying to create a JavaScript code that validates user input based on certain rules. If the input does not meet the criteria, I want an error message to appear next to the text field. For instance, if the rule is that the first character must be a cap ...

Utilize the Discord SDK to broadcast a message to every channel within a server whenever a command is utilized

In the process of development, I have crafted a new command: ! sir snd all -hello Essentially, this particular command instructs to dispatch the message specified after " - " to every channel located on the server where the command is initiated. Here&apo ...

Provider not found: attrsProvider <- attrs

Encountering an issue while trying to access attributes from the child controller > Unknown provider: attrsProvider <- attrs Below is the code snippet: var app = angular.module('plunker', []); //parent controller app.controller('Ma ...