SharePoint Internals – Hristo Pavlov’s Blog

16 May, 2008

What you need to know about AllowUnsafeUpdates (Part 1)

In short here is how to deal with AllowUnsafeUpdates:

1) Don’t update SharePoint objects from your code behind on GET requests as if you do so your code will be exploitable via a cross-site scripting. If you understand the consequences of doing this and still want to do it then read below about how to use the AllowUnsafeUpdates property.

2) 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. To find out more about this read the second part of this article.

 

The Microsoft idea behind introducing the AllowUnsafeUpdates property is to protect YOU from cross-site scripting attacks. The way this works is that if your application is running in an HTTPContext (i.e. it’s a web part for instance) and the request is a GET request then SharePoint will refuse to do any changes unless the value of AllowUnsafeUpdates is set to true and by default it will be false for GET requests. If you try to do any updates to lists, webs or any SharePoint objects that require an SPSite to be created first, and if you don’t set AllowUnsafeUpdates to true you will get this exception:

System.Exception: Microsoft.SharePoint.SPException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. —> System.Runtime.InteropServices.COMException (0x8102006D): The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.

It is important to understand that if you are writing a class library for example, your code will behave differently when called from a web application and when called from a rich client. Actually 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.

Usually when you create your own SPSite or SPWeb objects, i.e. when you are not getting them from the SPContext (such as SPContext.Web), and when you try to update anything such as web or list properties, list items metadata etc, you may get the exception listed above. This is a clear indication that AllowUnsafeUpdates of the SPWeb is false and this is preventing you from doing the update. This problem is resolved easily by setting the AllowUnsafeUpdates of the parent web object to true. Still sometimes even after you have done this you may still be getting the same error.  This is typically caused by one of the the following reasons:

A) You have set the AllowUnsafeUpdate to true for the wrong SPWeb

You have to be careful because sometimes the ParentWeb of an object is not the same instance of the web you have retrieved the object from. For example when you go initialWeb.Lists[listId] you would expect that the returned list’s ParentWeb instance is the same as you initialWeb. However this is not the case. So if somewhere later in your code you go list.ParentWeb.UpdateSomething() this will not work because you have never set the AllowUnsafeUpdates property of list.ParentWeb. You have set it for your initialWeb but even that this is the same web as the list’s parent web both are different instances. Usually you see the error and then you go and investigate in Reflector whether this is the same instance or not. Alternatively you could use another more generic and clever way to deal with almost any similar situation described in the following post:

http://community.bamboosolutions.com/blogs/bambooteamblog/archive/2008/05/15/when-allowunsafeupdates-doesn-t-work.aspx

The author suggests that you can set the HttpContent.Current to null before you do your updates and then reassign its initial preserved value when done. This will work great but remember to set the HTTPContent to null as early as possible. In the post above probably SharePoint uses the site.RootWeb to do the updates to the site scoped features and the RootWeb’s AllowUnsafeUpdates hasn’t been set to true explicitly.

B) The AllowUnsafeUpdates gets reset to false sometimes after you have set it to true

If we have a look at how the property is managed it turns out that it is stored in the request object associated with every SPWeb (which is actually a COM object)

[SharePointPermission(SecurityAction.Demand, UnsafeSaveOnGet = true)]

private void SetAllowUnsafeUpdates(bool allowUnsafeUpdates)

{

     this.Request.SetIgnoreCanary(allowUnsafeUpdates);

}

This actually means that every time the request is reset, the property will be also reset to its default value. The m_Request member is modified when a new web is created, when the web is disposed or when the SPWeb.Invalidate() method is called.

internal void Invalidate()

{

   if (this.m_Request != null)

   {

      if (this.m_RequestOwnedByThisWeb)

      {

         SPRequestManager.Release(this.m_Request);

      }

 

      this.m_Request = null;

   }

 

   this.m_bInited = false;

   this.m_bPublicPropertiesInited = false;

   this.m_Url = null;

}

So any operation that calls SPWeb.Invalidate() will reset AllowUnsafeUpdate to its default value. And for code running under HTTPContext, i.e. web applications, this default value for a GET request will be false. I’ve looked up for you all legitimate cases for which Invalidate() is being called by the SharePoint object model. These cases are:

1) When the Name or the ServerRelativeUrl properties of the SPWeb are changed and then Update() is called. In this case the AllowUnsafeUpdate is reset because with the change of these properties the URL of the web will change and logically the request object will change as it will now point to a different URL.

2) 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.

3) In many cases when an exception is caught by the SharePoint object model when you try to retrieve any sort of data the AllowUnsafeUpdates of the parent web will be reset to false as a precaution to protect against potential exploits. In those cases however the objects will be in unknown state anyway after the request has been reset and the exception is re-thrown so they are of no practical interest.

And finally it is also good to mention that you may get another related exception when trying to update your SharePoint objects and that is:

System.Exception: Microsoft.SharePoint.SPException: Cannot complete this action.Please try again. —> System.Runtime.InteropServices.COMException (0x80004005): Cannot complete this action.

This usually happens when some updates have been made to an object (usually SPSite, SPWeb or SPList) that may be clashing with your changes and SharePoint refuses to do the update. To recover from this situation you simply need to create fresh copies of the SPSite and the SPWeb objects and do the updates on the objects retrieved from the fresh copies. And of course don’t forget to set the AllowUnsafeUpdates to true for the freshly created SPWeb if required.

About these ads

32 Comments »

  1. [...] scripting. If you understand the consequences of doing this and still want to do it then see the first part of this article about how to use the AllowUnsafeUpdates [...]

    Pingback by What you need to know about AllowUnsafeUpdates (Part 2) « SharePoint Internals - Hristo Pavlov’s Blog — 21 May, 2008 @ 1:20 am

  2. Excellent Article

    Comment by stefan demetz — 26 May, 2008 @ 9:46 pm

  3. [...] What you need to know about AllowUnsafeUpdates (Part 1) [...]

    Pingback by SharePoint, SharePoint and stuff : SharePoint Kaffeetasse #70 — 28 May, 2008 @ 8:16 am

  4. Great Post! Cleared up a lot of conceptual questions

    Comment by techdhaan — 5 June, 2008 @ 8:23 am

  5. [...] What you need to know about AllowUnsafeUpdates (Part 1) What you need to know about AllowUnsafeUpdates (Part 2) [...]

    Pingback by Points to Share from Venkat Varkala » Code Acceptance checklist for Custom MOSS Solutions — 19 August, 2008 @ 4:44 pm

  6. [...] Also note – You may still need to set the AllowUnsafeUpdates property of the SPWeb object to True in some situations. See more here. [...]

    Pingback by Aptera Blog » Blog Archive » Accessing Secured SharePoint Lists with Elevated Privileges — 28 August, 2008 @ 12:20 pm

  7. superb article, you have taken everything in very good detail. Sharepoint COM exceptions are mainly confusing and no one is able to guess what went wrong, this article will help us in using power of AllowUnsafeUpdate property in safe manner :)

    Comment by sudhir kesharwani — 16 October, 2008 @ 4:09 am

  8. [...] July 2008 – updated with #5 above and found this interesting blog post on the subject from Hristo Pavlov’s Blog. This entry was posted in security, web and tagged [...]

    Pingback by Sharepoint, WSS and MOSS application development and security testing — 6 December, 2008 @ 6:44 am

  9. [...] Security Validation and Unsafe Updates Thursday, December 18th, 2008 | sharepoint | Trent Seeing this? The security validation for this page is invalid. I am sure this error has good intentions, but it is showing its face far to often. Hristo Pavlov has written a good explanation on AllowUnsafeUpdates here. [...]

    Pingback by Security Validation and Unsafe Updates | Trentacular — 18 December, 2008 @ 7:25 pm

  10. [...] Check out Hristo Pavlov’s blog on AllowUnsafeUpdates here. [...]

    Pingback by Jake Opines : SharePoint Saturday: Developing and Packaging a Third Party SharePoint Solution — 12 January, 2009 @ 3:35 pm

  11. [...] I was still receiving this error. I did a bit of digging and came across some useful information Hristo Pavlov’s blog. His article is titled What You Need To Know About AllowUnsafeUpdates (Part 1) and is a must [...]

    Pingback by Understanding BreakRoleInheritance() Can Reset AllowUnsafeUpdates | SharePoint Fun — 31 January, 2009 @ 3:35 pm

  12. [...] What you need to know about AllowUnsafeUpdates (Part 1) [...]

    Pingback by Huimiao's Blog - .NET and SharePoint : SharePoint ??-1 — 21 March, 2009 @ 8:01 am

  13. [...] transparent here, I am not convinced that this is the only way to accomplish this, and recognize the risk in opening up the site for unsafe updates even for a brief period of time.  Even though our code is only allowing unsafe updates for a [...]

    Pingback by Kirk Evans Blog : SharePoint for Developers Part 6 – Custom web services — 30 April, 2009 @ 9:01 am

  14. [...] transparent here, I am not convinced that this is the only way to accomplish this, and recognize the risk in opening up the site for unsafe updates even for a brief period of time.  Even though our code is only allowing unsafe updates for a [...]

    Pingback by SharePoint for Developers Part 6 – Custom web services | Coded Style — 30 April, 2009 @ 10:37 am

  15. [...] does and why I use it. I came across a very detailed article, that explained I could use ValidateFormDigest instead of this little [...]

    Pingback by Adding Items to a SharePoint List. « Kobi’s Weblog — 4 May, 2009 @ 3:31 pm

  16. realy it’s great post…
    thanks

    Comment by khaled abrass — 21 May, 2009 @ 2:08 pm

  17. [...] The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. at Microsoft.SharePoint.Library.SPRequestInternalClass.ValidateFormDigest(String bstrUrl, String bstrListName) at Microsoft.SharePoint.Library.SPRequest.ValidateFormDigest(String bstrUrl, String bstrListName)    http://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/ [...]

    Pingback by Sharepoint running notes « code siblings,adventures,songs and excerpts of my daily work — 27 May, 2009 @ 5:44 am

  18. [...] This can happen especially if you use this kind of code in a loop where you´ll re-use the web or somehow that web object gets its AllowUnsafeUpdates back to false somewhere else in the code. More about this can be read here: http://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/ [...]

    Pingback by RunWithUnsafeUpdates « Johan Leino — 7 August, 2009 @ 8:14 pm

  19. [...] What you need to know about AllowUnsafeUpdates (Part 1) [...]

    Pingback by Error message in WSS 3.0: "The security validation for this page is invalid" « In The Mix — 1 September, 2009 @ 11:46 pm

  20. Nice article! it helps me a lot!

    Comment by Harjet — 16 September, 2009 @ 4:37 pm

  21. Excelent article! it helps me a lot!

    Comment by Samarendra Swain — 9 December, 2009 @ 2:37 pm

  22. [...] After doing some digging on the internet I discovered a blog by Hristo Pavlov about AllowUnsafeUpdates. [...]

    Pingback by MOSS 2007 Workflow SpecialPermission Bug - Andy Hoffman's Lab — 15 January, 2010 @ 9:46 pm

  23. [...] What You Need To Know About AllowUnsafeUpdates [...]

    Pingback by Is AllowUnsafeUpdates=true the right way? « — 24 February, 2010 @ 8:46 am

  24. Making Updates to SharePoint from JavaScript…

    While working on a project involving SharePoint, our effort to provide a better UI required making some updates from JavaScript. If you make an attempt at this you are likely to get the following e ……

    Trackback by Coding Adventures Web Log — 2 March, 2010 @ 6:38 am

  25. Thanks for posting these research results – indispensible!

    Comment by Michael Keister — 24 March, 2010 @ 6:00 pm

  26. [...] What you need to know about AllowUnsafeUpdates (Part 1) [...]

    Pingback by Kit Menke's Blog » Blog Archive » AllowUnsafeUpdates and ValidateFormDigest — 24 June, 2010 @ 2:50 am

  27. SharePoint – Обновления данных в списках системой…

    Item["Status"] = “Pending”; Item.Web.AllowUnsafeU ……

    Trackback by Q-A Ковров — 22 February, 2011 @ 8:10 pm

  28. Hello! I had the same problems with BreakRoleInheritance and used the same workaround. I described it in my blog
    http://dotnetfollower.com/wordpress/2011/03/sharepoint-updates-are-currently-disallowed-on-get-requests/

    Comment by .Net Follower — 21 May, 2011 @ 3:21 am


RSS feed for comments on this post. TrackBack URI

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

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: