Saturday, August 23, 2008

Reminder: AllowUnsafeUpdates Issues

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

When to use?
If your application is running in an HTTPContext (for instance an application page, web part, ...) and the request is a GET request, SharePoint will refuse to do any changes. For this reason you will have to set the AllowUnsafeUpdates to true. Note: By default that property is set to false for GET requests.

When not to use?
In a console application, class library, ... where the HTTPContext.Current is null - AllowUnsafeUpdates will be always true. So you don't have to set this property.

What about breaking role definition inheritance?
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.

Bad piece of code:

SPList sharedPictures = curWeb.Lists["Shared Pictures"];
sharedPictures.Title = "My Pictures";
curWeb.AllowUnsafeUpdates = true;
//--> no help!
sharedPictures.BreakRoleInheritance(true);
ReducePermissonsOnLibrary(sharedPictures);
//---> crash!

Exception will be probably: Updates are currently disallowed on GET requests. To allow updates on a GET,set the 'AllowUnsafeUpdates' property on SPWeb.

Working piece of code:

SPList sharedPictures = curWeb.Lists["Shared Pictures"];
sharedPictures.Title = "My Pictures";
sharedPictures.BreakRoleInheritance(true);
CurWeb.AllowUnsafeUpdates = true; //BreakRoleInheritance set AllowUnsafeUpdates back to false!
ReducePermissonsOnLibrary(sharedPictures);


Conclusion: Always set AllowUnsafeUpdates back to true after you break inheritance in an environment with HTTPContext.

AllowUnsafeUpdates and Try/Catch
Steven Van de Craen wrote about this issue.

Resources:

What you need to know about AllowUnsafeUpdates (Part 1)
What you need to know about AllowUnsafeUpdates (Part 2)

2 comments:

jopx said...

Apparently you found the solution :-) ...

kissliy said...

This comment "//BreakRoleInheritance set AllowUnsafeUpdates back to false!" resolve my problems :)
Thanks great!