If you’re building a MVC application and you find that your QA team has reported the following, “anti-forgery token”, behaviour, read on for a possible solution: Anti-forgery token was meant for user “” - Microsoft MVC application development

The provided anti-forgery token was meant for user “”, but the current user is “myUsername”.

Scenario

A user lands on the login page, they then enter valid credentials and click on the login button.

After authenticating successfully the user is redirected to another application page but for some reason the user clicks the browser back button. After re-entering their credentials again and clicking the login button they get the following exception:

The provided anti-forgery token was meant for user “”, but the current user is “myUsername”.

Anti-forgery token error – Possible Solution

One approach to avoiding this issue is to ensure that the Login action returns no-cache instructions to the browser. You do this by adding an OutputCache directive to the Action as follows:

[OutputCache(NoStore=true, Duration = 0, VaryByParam= “None”)]
public ActionResult Login(string returnUrl, string token = “”)

Test It

You can test this by putting a break point on the first line of your Login (Get) action. Before adding the OutputCache directive the breakpoint would be hit on the first load, but after clicking the browser back button it wouldn’t. After adding the directive (and clearing your browser cache) you should end up with the breakpoint being hit every time.