Friday, January 05, 2007

ASP.Net 2.0 Event Validation Exception / The Why and the How

There is a new feature in ASP.Net 2.0 called Event Validation. Its value (EnableEventValidation) is true by default. If you upgraded from 1.1 to 2.0, your site may stop working.

The purpose of this feature is to protect your site from illegal values from being posted. For instance, let's say your have a drop down list with 3 values "0,1,2".
It is possible to construct a post (hacking) to post a value "3" for this drop down.
Indeed, the drop down simply generates a <select> element on the browser and is simple to alter.

Now, this rogue "3" may not be very serious for this example but all posted values
could be subject to change and force your application to do something that was
not intended.
In ASP.Net the event validation just checks that the value that is posted was actually in the list of values in the drop down. In other words, if a hacker posted "3" the framework would throw an exception since the initial list was "0,1,2".

Most of the time, you do not have to worry about it since you do not intentionaly
post bad values. However, once you start manipulating the DOM on the browser, you could for instance dynamically add a "3" to your <select> and the user could click on it.

As we move to more code on the client (the AJAX thing), you can see how this could happen. An asynchronous post back for instance could fetch data and you could add more options to your <select>.

If you know you may post values that were not in the initial list, you need to
call ClientScript.RegisterForEventValidation(). In this case you would do this:
ClientScript.RegisterForEventValidation(yourDropDown.UniqueID,"3").

Now, I have code that broke from 1.1 to 2.0. The reason was this. We created some javascript that used the __doPostBack() but we typed it manually. In other words, we were not using the GetCallBackReference() API that returns the javascript code to raise an event on the server. So we violated the framework's intent.

If you use Reflector and look at the GetCallBackReference(), you will see that
it uses the RegisterForEventValidation() and takes care of its business.

The conclusion is that the framework does a lot of work for you. Use it as intended or pull your hair for hours trying to figure out what's going on.





__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com