Beware: Upgrade to ASP.NET MVC 2.0 with care if you use AntiForgeryToken

Posted by James Crowley on ASP.net Weblogs See other posts from ASP.net Weblogs or by James Crowley
Published on Thu, 18 Mar 2010 13:02:00 GMT Indexed on 2010/03/18 13:21 UTC
Read the original article Hit count: 916

Filed under:
|
|

If you're thinking of upgrading to MVC 2.0, and you take advantage of the AntiForgeryToken support then be careful - you can easily kick out all active visitors after the upgrade until they restart their browser. Why's this?
For the anti forgery validation to take place, ASP.NET MVC uses a session cookie called "__RequestVerificationToken_Lw__".

This gets checked for and de-serialized on any page where there is an AntiForgeryToken() call. However, the format of this validation cookie has apparently changed between MVC 1.0 and MVC 2.0.
What this means is that when you make to switch on your production server to MVC 2.0, suddenly all your visitors session cookies are invalid, resulting in calls to AntiForgeryToken() throwing exceptions (even on a standard GET request) when de-serializing it:

[InvalidCastException: Unable to cast object of type 'System.Web.UI.Triplet' to type 'System.Object[]'.]
   System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken) +104

[HttpAntiForgeryException (0x80004005): A required anti-forgery token was not supplied or was invalid.]
   System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken) +368
   System.Web.Mvc.HtmlHelper.GetAntiForgeryTokenAndSetCookie(String salt, String domain, String path) +209
   System.Web.Mvc.HtmlHelper.AntiForgeryToken(String salt, String domain, String path) +16
   System.Web.Mvc.HtmlHelper.AntiForgeryToken() +10
  <snip>


So you've just kicked all your active users out of your site with exceptions until they think to restart their browser (to clear the session cookies).

The only work around for now is to either write some code that wipes this cookie - or disable use of AntiForgeryToken() in your MVC 2.0 site until you're confident all session cookies will have expired. That in itself isn't very straightforward, given how frequently people tend to hibernate/standby their machines - the session cookie will only clear once the browser has been shut down and re-opened.

Hope this helps someone out there!

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about .NET