1

In my application sometimes i get the exception when I try to log in:

A required anti-forgery token was not supplied or was invalid.

I can't reproduce it in 100%, but it happens frequently.

My guess is that is has something to do with multiple login forms on the same page.

More precisely:

  • On top of my page there is a small log in/out panel always visible.

  • If the unauthorized user tries an action he's not supposed to, he gets redirected to a dedicated log in page.

  • Than there are 2 different forms pointing to the same action.
  • Both forms have:

    @Html.AntiForgeryToken()

  • The log in action is decorated with:

    [ValidateAntiForgeryToken]

My questions:

  1. Can this be the problem?
  2. If not, than what can it be?
  3. And of course how to fix it?

Please note that:

  • This top log in/out panel is in a partial, which is in a partial ... which is in the _Layout.cshtml
  • The dedicated log in page is rendered as a body.
Andrzej Gis
  • 13,706
  • 14
  • 86
  • 130
  • Have you looked at this SO question about troubleshooting [anti-forgery tokens](http://stackoverflow.com/questions/5767768/troubleshooting-anti-forgery-token-problems)? – neontapir Dec 17 '13 at 22:31
  • Why not just not display the top login bar on the dedicated login page as a test? – Tommy Dec 17 '13 at 22:41
  • @Tommy it would be inconclusive as like I said I can't reproduce it 100% actually it happens in like 20% of the log in attempts. – Andrzej Gis Dec 17 '13 at 22:46
  • @gisek - are you sure that this is the page that is causing it? I have found that expired logins can sometimes create bad anti-forgery request as well (if the login cookie expired) or if you do not have your machine key set to a static key (meaning set to auto-generate) – Tommy Dec 17 '13 at 22:48
  • @Tommy I'm not sure of anything here actually :) We can exclude login cookie expiration as it occured on machines that visited the page for the first time. My machine key is static - set in Web.config – Andrzej Gis Dec 17 '13 at 22:55
  • It has something to do with cookies. The server checks 2 tokens: 1 from cookeis and 1 from the psoted form. Apparently they don't match. – vortexwolf Dec 17 '13 at 23:06

0 Answers0