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.
Pingback: When & why I need to use web.AllowUnsafeUpdates = true | DL-UAT
Pingback: SharePoint | Bits and Bytes » Is SPWeb.AllowUnsafeUpdates an expensive process?