Saturday, September 29, 2007

AllowUnsafeUpdates, a Sharepoint Object Model gotcha

The other day I was trying to programatically add group to SharePoint via the object model and a confusing exception would continue to get thrown. This same exception could happen whenever you are trying to add an SPUser, SPWeb, Group etc... to an existing collection via the SharePoint object model.

I would run some code that looked a little like:

SPMember owner = rootWeb.Users["SomeUserName"];
SPUser user = rootWeb.Users["SomeUserName"];
rootWeb.SiteGroups.Add(groupName, user, null, description);

And the following exception would get thrown:

System.Runtime.InteropServices.COMException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.

After digging around I discovered that you need to set SPWeb.AllowUnsafeUpdates = true. I have yet to find out the implications of this setting although the MSDN states that

"Setting this property to true opens security risks, potentially introducing cross-site scripting vulnerabilities."
The good news is that after you call Dispose on your SPWeb object and get a new one the setting is reset to false.

No comments: