How to make your ViewState secure?

ASP.Net viewstate is client side state management and is stored in hidden field with id __VIEWSTATE as shown below:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjkPFgYLl/p5/cggNdr/yAizfkifBJ20CwQ=" />

Now the string in value is is not encrypted but serialized(encoded) use Base64 en ccoding, which can be easily decoded using many tools.

Now there are mainly two approach to secure your Viewstate:
1) EnableViewStateMAC / Hash code (Hashing)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataSetToViewState.aspx.cs"
EnableViewState="true" EnableViewStateMac="true" Inherits="WebWorld.DataSetToViewState" %>

Make sure viewstate data is tamper proof using Hash Code, you can do this by adding EnableViewStateMAC=true. MAC stands for Message Authentication Code. It internally added a Hash code with ViewState content and store in hidden field. During postback, the checksum data is verified again by ASP.Net and if there is mismatch, the postback will be rejected.
2) Encryption

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataSetToViewState.aspx.cs"
EnableViewState="true" ViewStateEncryptionMode="Always" Inherits="WebWorld.DataSetToViewState" %>

The second option ViewStateEncryptionMode=”Always”. It will encrypt the viewstate, there are three option
Always: Encrypt the viewstte always.
Auto: Encrypt if the control require for encyrption. For this to happen, the control must call the Page.RegisterRequiresViewStateEncryption() method.
Never: Never encrypt the viewtate.

We can also enable these settings for EnableViewStateMAC and ViewStateEncryptionMode in web.config:

<system.web>
<pages enableViewStateMac="true" viewStateEncryptionMode="Always"></pages>
</system.web>

Note: Try to avoid ViewState encryption if it is not necessary as it can cause performance issues.

References:
http://www.codeproject.com/Articles/150688/How-to-make-ViewState-secure-in-ASP-NET

Advertisements

Leave a comment

Filed under ASP.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s