How to Fix Cross-site Request Forgery Vulnerability(CSRF)

Posted by on May 1, 2012 0 Comment

Cross-Site Request Forgery (CSRF) is an attack that allows a hacker to perform an action on the vulnerable site on behalf of the victim. The attack is possible when the vulnerable site does not properly validate the origin of the request.

The attack is performed by forcing the victim’s browser to issue an HTTP request to the vulnerable site. If the user is currently logged-in to the victim site, the request will automatically use the user’s credentials (like session cookies, user’s IP address, and other browser authentication methods). Using this method, the attacker forges the victim’s identity and submits actions on his or her behalf. In other words, the vulnerable site does not take the proper measures to validate that the user indeed wanted to perform the specific action.

CSRF protection can be achieved through the use of the Synchronizer Token Pattern. While again a filter or even a listener could be used to rely on simple Controller logic.

OWASP’s CSRF Guard can be used to automatically include such tokens in your Java EE, .NET, or PHP application.


Viewstate can be used as a CSRF defense. If the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF.

To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)

protected override OnInit(EventArgs e) {
     if (User.Identity.IsAuthenticated)
        ViewStateUserKey = Session.SessionID; }

The following keys the Viewstate to an individual using a unique value of your choice.


This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded.