Monday, March 15, 2010

SharePoint SPSite.AllowUnsafeUpdates

The Microsoft idea behind introducing the AllowUnsafeUpdates property is to protect you from cross-site scripting attacks.

MSDN Definition: 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.

If you try to do any updates to lists, webs or any SharePoint objects that require an SPSite to be created first, you need to set AllowUnsafeUpdates to TRUE, otherwise it will through an error saying "System.Exception: Microsoft.SharePoint.SPException: The security validation for this page is invalid."

In order for the AllowUnsafeUpdates to work, that the Update method of the SPSite object needs to be called as well:

SPSite.AllowUnsafeUpdates = true;
SPSite.Update();

Also, you may want to try using a POST, rather than a GET in order to avoid having to set this property. If your code is processing a POST request then make sure you call SPUtility.ValidateFormDigest() before you do anything else. This will ensure that the post request is validated (that it is not a cross-site scripting attack) and after that you will not have to worry about AllowUnsafeUpdates, because its default value will be “true” after the form digest is validated.

If the HTTPContext.Current is null then AllowSafeUpdates will be always true. This is the case in rich clients where no cross-scripting is possible as there are simply no web requests.

When any object that implements ISecurable (those are SPWeb, SPList and SPListItem) breaks or reverts their role definition inheritance. This means every time you call SPRoleDefinitionCollection.BreakInheritance(), BreakRoleInheritance(), ResetRoleInheritance() or set the value of HasUniquePerm the AllowUnsafeUpdates property of the parent web will reset to its default value and you may need to set it back to true in order to do further updates to the same objects. So always set AllowUnsafeUpdates back to true after you break inheritance in an environment with HTTPContext.

Additional References:

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.allowunsafeupdates.aspx
http://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/
http://hristopavlov.wordpress.com/2008/05/21/what-you-need-to-know-about-allowunsafeupdates-part-2/

0 comments: