SPWeb.AllowUnsafeUpdates

Introduction

In this article I am going to explain you that How and when to use SPWeb.AllowUnsafeUpdates.

SPWeb.AllowUnsafeUpdates : It 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. Whenever your code modifies SharePoint data in some way or Whenever we need to update SharePoint objects like SPWeb, SPList, SPListItem, etc , without requiring a security validation, we need to set SPWeb.AllowUnsafeUpdates = true.
Following is the code snippet for the same.

1
2
3
4
5
SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
 
// Perform the list/list item/web update 
web.allowUnsafeUpdates = false;


Detail:-

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.

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 thatAllowUnsafeUpdates of the SPWeb is false and this is preventing you from doing the update. This problem is resolved easily by setting theAllowUnsafeUpdates of the parent web object to true.

Few examples:- Scenario 1 (using SPWeb.EnsureUser):-

EnsureUser looks for the specified user login inside SPWeb.SiteUsers collection, and if the login isn’t found, turns toActiveDirectory for the purpose of retrieving the user information from there. If such information is found, it will be added to SPWeb.SiteUsers and for the next time it will be returned directly fromSPWeb.SiteUsers. That means we are modifying SPWeb by adding user. Therefore we need to use AllowUnsafeUpdates property to avoid exception.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static SPUser VerifyUser(SPWeb web, string loginName)
{
    SPUser myUser = null;
	try
	{
		web.AllowUnsafeUpdates = true;
		myUser = web.EnsureUser(loginName);
	}
	catch (Exception ex) {// write to log}
	finally
	{
		web.AllowUnsafeUpdates = oldAllowUnsafeUpdate;
	}
    return myUser;
}


Scenario 2 (using BreakRoleInheritance):-

When we use Methods BreakInheritance, ResetRoleInheritance and BreakRoleInheritance, it reset AllowUnsafeUpdates to false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using (SPSite spSite = new SPSite("url"))
{
    using (SPWeb spWeb = spSite.OpenWeb())
    {
        bool oldAllowUnsafeUpdates = spWeb.AllowUnsafeUpdates;
 
        try
        {
		SPList spList = spWeb.Lists["some list"];
		SPListItem spLisItem = spList.GetItemById(someId);
		// need to set since we are going to modify SPListItem
		spWeb.AllowUnsafeUpdates = true; 
		spLisItem.BreakRoleInheritance(false);
 
		SPRoleDefinition reader = spWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
		SPGroup someGrp = spWeb.Groups["some group"];
 
		SPRoleAssignment roleAssignment = new SPRoleAssignment(someGrp);
		roleAssignment.RoleDefinitionBindings.Add(reader);
 
		// need to set since BreakRoleInheritance method reset AllowUnsafeUpdates to false
		spWeb.AllowUnsafeUpdates = true;
		spListItem.RoleAssignments.Add(roleAssignment);
 
        }
        catch (Exception ex)
        {
            // logging
        }
 
        spWeb.AllowUnsafeUpdates = oldAllowUnsafeUpdates;
	spWeb.Update();
    }
}


Scenario 3 (using SPListItem.Update):-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using (SPSite spSite = new SPSite("url"))
{
    using (SPWeb web = spSite.OpenWeb())
    {
        try
        {
			SPList list = web.Lists["SomeList"];
			SPListItem item = list.GetItemById(12);
			item["Title"] = "Some Changes";
			web.AllowUnsafeUpdates = true;
			item.Update();
			web.AllowUnsafeUpdates = false;
        }
        catch (Exception ex)
        {
            // handle exception
        }
     }
}


Reference
:-


http://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/

http://dotnetfollower.com/wordpress/tag/allowunsafeupdates/
http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/a4729dbb-1527-44d9-92ae-3f3489945e84/
http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/984d422f-abda-41d9-93ed-c6a2b6fb9413

Thanks!
Avinash

calendarMarch 24, 2012 ¬∑ cardInfoyen ¬∑ commentsOne Comment
tagTags: , , , , , ,  ¬∑ Posted in: MOSS, Security, SharePoint

One Response

  1. Sasi Kumar Reddy - September 1, 2012

    Best reference to know.

Leave a Reply

Spam Protection: , required

myworldmaps infoyen