Why do I need to use SPWeb.AllowUnsafeUpdates?

We have a customer who has a couple of custom feature bound onto a WebTemplate that was giving them grief when they attempted to provision sites from this template via PowerShell but worked just fine when using the web UI.

What the team was experiencing was that during the activation of certain features errors with the message “The security validation for this page is invalid”. Now the fix is simple, set AllowUnsafeUpdates=true during the custom feature activated code.

But why do we need to do this?

First let’s look at what’s happening in the context of making these changes via the web UI. In SharePoint there is a FormDigest control, this control places some security validation information into the page which is included in the POST back to the server. SharePoint uses this information to verify that this request to change the contents of its databases does correspond to a request from a page that was served up by SharePoint.

Now when we attempt to make these changes from custom code that’s getting executed from PowerShell there’s no page, no POST and no form digest information bundled along. So SharePoint attempts to verify the form digest a.k.a “security validation” and in the interests of self protection quite rightly throws an exception. This behaviour of SharePoint wanting it’s changes to come from a web browser can also present via the message “Updates are currently disallowed for GET requests”.

Of course because what we’re trying to do here is a valid use case SharePoint supports disabling these checks via the AllowUnsafeUpdates property on the SPWeb object. Now because setting this property to true opens up potential security risks you shouldn’t just set it to true and leave it that way, just toggle it for while you need to make these changes and flip it back to the way it was.

bool unsafeUpdates = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;
//make some changes;
web.AllowUnsafeUpdates = unsafeUpdates;

Hopefully this has helped to explain the WHY behind the use of AllowUnsafeUpdates that you’ll often see in custom server side code.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Why do I need to use SPWeb.AllowUnsafeUpdates?

  1. Pingback: When & why I need to use web.AllowUnsafeUpdates = true | DL-UAT

  2. Pingback: SharePoint | Bits and Bytes » Is SPWeb.AllowUnsafeUpdates an expensive process?

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