SharePoint–AllowUnsafeUpdates when using Object Model to Update Security

I have some code that will programmatically add a group to SharePoint via the object model.  When running this code I kept getting an error that I couldn’t do this.  The error/exception would get thrown whenever trying to add permissions to an existing collection via the SharePoint object model – apparently SharePoint Security likes to keep things in the UI.

I would run some code that looked a little like:

SPMember owner = rootWeb.Users["UserName"];
SPUser user = rootWeb.Users["UserName"];
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.

"Setting this property to true opens security risks, potentially introducing cross-site scripting vulnerabilities."

So just a quick reminder that any time you want to deal with the Security of a site in the ObjectModel, always turn on the AllowUnsafeUpdates and when you’re done with it, set it back to false.

EDIT: If you forget to set it to false, never fear… After the object is disposed and you get another SPWeb the setting is set back to false.

Leave a Reply