title: MVC5 AntiForgeryToken - how to handle "The provided anti-forgery token was meant for user "", but the current user is "xxx"." exception?
body: <p>I want to protect our login actions by <strong>AntiforgeryToken</strong> attribute - I know why the exception from the topic occurs, however I can't seem to find any good solution for it.</p>
  
  <p>Let say we have the following situations:</p>
  
  <ol>
  <li><p>It's 8:00 AM, application users are coming to work, they sit down and starting the login process - right now it is <strong>very possible</strong> that some of the users will get the same <strong>ValidationToken</strong>. After the first one logs in - all other will see the above exception (or some other custom exception screen) when they attempt to login.</p></li>
  <li><p>Some user logged in, then accidentally pressed the "<strong>back</strong>" button and attempted to log in again - while this is more unlikely, it can happen, and I don't want users to see exceptions when it does.</p></li>
  </ol>
  
  <p>So the question is simple - <strong>how to prevent the above situations, or how to handle them so that users won't notice anything</strong>. I have tried the following:</p>
  
  <ol>
  <li>Setting the <strong>AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;</strong> in <strong>Application_Start in Global.asax</strong> - it <strong>didn't fix the problem</strong>, I still get the same exception</li>
  <li>Setting the <strong>[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]</strong> on the method with <strong>[ValidateAntiForgeryToken] attribute</strong> - <strong>again, no luck there</strong></li>
  </ol>
  
  <p>Right now I was thinking to <strong>manually validate the token in action body</strong>, catch the error, and check if attempt was made by anonymous user: </p>
  
  <pre><code>public ActionResult SomeAction()
  {
      try
      {
          AntiForgery.Validate();
      }
      catch(HttpAntiForgeryException ex)
      {
          if(String.IsNullOrEmpty(HttpContext.User.Identity.Name))
          {
              throw;
          }
      }
  
      //Rest of action body here
      //..
      //..
  }
  </code></pre>
  
  <p>The above seems to prevent the errors - <strong>but is it safe?</strong> <strong>What alternatives are there?</strong></p>
  
  <p>Thanks in advance.</p>
  
  <p>Best regards.</p>
  
  <p>EDIT:</p>
  
  <p>The final "solution" was to disable token validation on login form - there may be a better way to handle it, but it seems that all solutions I found, were ugly workarounds similar to mine proposed above. </p>
  
  <p>Since there is no way to know how "safe" those alternatives are (if they are safe at all), we decided to do disable token validation on login.</p>