How to make ViewState secure in ASP.NET ? January 26, 2011Posted by Abhijit Jana in ASP.NET, Tips and Tricks.
Tags: ASP.Net, codeproject, How To
The ASP.NET ViewState is a client side state management. ViewState is stored in hidden field with ID named __VIEWSTATE. Typically, stored ViewState information looks as below:
Now let us look at the value. It looks likes an encrypted string. This is nothing but Base64 Encoded string and it is not an encrypted string. So it can be easily decoded.
The main reasons for making it Base64 encoding are as follows:
1. Base64 makes a string suitable for HTTP transfer
2. It makes it a little harder to read .
But people often get confused that this is an encrypted string.
Let us try to decode the string using ViewState Decoder (A nice tool created by Fritz Onion).
After decoding the string, we can see the exact data that is stored inside the ViewState.
You can write few lines of code to decode the text and you will get the exact view state information.
So here is how the ViewState Works,
By default, ViewState is serialized into a base-64 encoded string. On PostBack, the ViewState information is loaded and reapplied to the persisted state of the Control in the Control Hierarchy.
There are two different ways in which you can prevent someone from decrypting the ViewState data.
1. You can make sure that the view state information is tamper-proof by using “hash code“. You can do this by adding “EnableViewStateMAC=true” in your page directive. MAC Stands for “Message Authentication Code”
When we use EnableViewStateMac=”True”, during ViewState save, ASP.NET internally used a hash code. This hash code is a cryptographically strong checksum. This is added with the ViewState content and stored in hidden filed. During post back, the checksum data is verified again by ASP.NET. If there are some mismatches, Post back will be rejected.
2. Second option is to set ViewStateEncryptionMode=”Always” with your page directives. This will encrypt the view state data. You can do this in the following way:
The ViewStateEncryptionMode has three different options that can be set:
- Always : encrypt the view state always
- Auto : encrypt if any control requests specifically for encryption . For this to happen, the control must call Page.RegisterRequiresViewStateEncryption() method to request encryption.
- Never : Never encrypt the ViewState data
If you make the ViewStateEncryptionMode=”Always” and try to decode the ViewState data, you will get information as shown below.
We can also enable these settings for “EnableViewStateMAC” and ViewStateEncryptionMode” in web.config .
Note: Try to avoid ViewState Encryption if it is not necessary as it can cause the performance issues.
If you are a beginner with ViewState, please read my article on ViewState – Beginner’s Guide To View State