2

I've implemented the antiforgerytoken in my MVC 2 app.
I have also added a machine key in the web.config. When the session expires and I try and do a post it throws a A required anti-forgery token was not supplied or was invalid error.
It seems like the antiforgery token is expiring.

My question is

  • Why is it throwing an error after session expiry?
  • How long is the token valid for?
balexandre
  • 73,608
  • 45
  • 233
  • 342
doogdeb
  • 403
  • 1
  • 4
  • 15

1 Answers1

3

I've never experienced such problem and I am pretty sure that the AntiForgeryToken do not expire but I was reading here and it seems that someone has had your problem.

I do not use the machine key. I simply do something like this:

<% using(Html.Form("UserProfile", "SubmitUpdate")) { %>
    <%= Html.AntiForgeryToken("AF-MyApp-token") %>
    <!-- rest of form goes here -->
<% } %>

and server-side:

[ValidateAntiForgeryToken(Salt="AF-MyApp-token")]
public ViewResult SubmitUpdate()
{
    // ... etc
}
LeftyX
  • 35,328
  • 21
  • 132
  • 193
  • It is very frustrating as there's not a whole lot you can mess up by implementing the antiforgery tokens in your app. Am I right in thinking that you simply add the machinekey to your web.config and they will automatically use it? – doogdeb Jun 01 '11 at 13:33
  • @doogdeb: I've updated my answer. I had got inspiration from here: http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-%20aspnet-mvcs-antiforgerytoken-helper/ – LeftyX Jun 01 '11 at 13:43
  • I've looked at that soluition before but I still had the same issue. Also my app is going to be deployed in a web farm so that's why I went the machinekey route. – doogdeb Jun 01 '11 at 13:48
  • 1
    @doogdeb: As I said I haven't experienced anything like that. But, anyway, the article that jamescrowley has written (see the link in my answer) has got a solution for that. – LeftyX Jun 01 '11 at 13:57
  • Firefox says that the __RequestVerificationToken_Lw__ cookie expires at the end of the session. I tested this in MVC3, but assume this behaviour is consistent in MVC2. – Richard Garside Sep 26 '11 at 10:47