Security Validation For This Page Is Invalid

Once time I wrote code for sharepoint, I got message error when tried to update item of certain list,

“The security validation for this page is invalid. Click Back in your Web browser.”

Actually, this is warning message to prevent our page from cross-site scripting attack or know by XSS. In general, cross-site scripting refers to that hacking technique that leverages vulnerabilities in the code of a web application to allow an attacker to send malicious content from an end-user and collect some type of data from the victim.

To handle that issue, simply set “AllowUnsafeUpdates” into True to code before updating list. From msdn, SPWeb.AllowUnsafeUpdate means Gets or sets a Boolean value that specifies whether to allow updates to the database as a result of a GET request or without requiring a security validation. Setting this property to true opens security risks, potentially introducing cross-site scripting vulnerabilities.. Then finalizing the update by set AllowUnsafeUpadates back to default value : False.

Good example:

using (SPSite site = new SPSite("http://www.controlzet.wordpress.com"))
{	
	using (SPWeb web = site.OpenWeb())
	{
		web.AllowUnsafeUpdates = true;
		SPList list = web.Lists["Custom List"];
		ListItem listItem = list.Items.Add();
		listItem["Title"] = "This is new item";
		listItem.Update();
		web.AllowUnsafeUpdates = false;
		return list;
	}
}

For some people out there, might encounter these solution is not helpful because not work well and issue still happen. One possible reason is because they make a method to get a list and update item from its return value.

Bad example:

private void MainMethod()
{
	using (SPSite site = new SPSite("http://www.controlzet.wordpress.com"))
	{
		using (SPWeb web = site.OpenWeb())
		{
			web.AllowUnsafeUpdates = true;
			SPList list = GetList("Custom List");
			ListItem listItem = list.Items.Add();
			listItem["Title"] = "This is new item";
			listItem.Update();
		}
	}
}

private SPList GetList(string listName)
{
   using (SPSite site = new SPSite("http://www.controlzet.wordpress.com"))
   {
        site.AllowUnsafeUpdates = true;
        using (SPWeb web = site.OpenWeb())
        {
            web.AllowUnsafeUpdates = true;
            SPList list = web.Lists[listName];
            return list;
        }
   }
}

Besides web context, SPSite also has property AllowUnsafeUpdates. We might use it when try to modify site collection related property (e.g creating/deleting site collection).

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s