3

I've one question, I recently put anti forgery token in all my forms and in my controller I put the ValidateAntiForgeryToken attribute.

But often my users fill a form, then came back with the browser button, make a correction in one of their mistakes, and they get the invalid anti-forgery token.

I can understand why it happens(we are going back and using an anti-forgery token that isn't valid anymore), but is there any way to avoid this behavior? Like force to reload this page?

J4N
  • 19,480
  • 39
  • 187
  • 340

2 Answers2

5

This is odd. Antiforgery tokens are NOT one time use tokens. They can generally be happily reused within the same session. Are your users logged in at the time? The token is based on login so if they've logged back in during this time the token may no longer be valid then.

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • Hum, yes, but I've a custom UserName provider. On what does it rely to detect it's another user? – J4N Jun 28 '12 at 14:48
  • See the username code: http://stackoverflow.com/questions/5767768/troubleshooting-anti-forgery-token-problems – Adam Tuliper Jun 28 '12 at 15:32
  • I'm sorry but I didn't understood this, what is this validate method? It isn't me which have access the way how asp.net validate token – J4N Jun 29 '12 at 06:56
  • no but if you are doing something custom that is making it fail then you'll have to debug this. The scenario you mentioned above with repeated posts works fine by default with the anti forgery tokens, so that fact something is failing means you'll have to do a little debugging with it. If you can repeat this and narrow down a test case you can easily grab the mvc source and step into it. If the username changes between requests this would cause a failure. – Adam Tuliper Jun 29 '12 at 20:23
0

The "redirect-after-post pattern" with TempData method should solve your issue.

The basic idea is you would put some value in TempData within your Action and check if that value is present. If the user has pressed the 'back button' or refreshed the page, the TempData value would no longer be present - you could check for this value and react appropriately (i.e. resubmit the action if you wish).

I could go into more detail, but this post by Darin Dimitrov sums it up appropriately

Community
  • 1
  • 1
Ecnalyr
  • 5,792
  • 5
  • 43
  • 89
  • I wish I could do this, but unfortunately, I've very strict pages on which I've to redirect after modification. – J4N Jun 28 '12 at 14:49