Exception encountered using SPSecurity.RunWithElevatedPrivileges
I am encountering an exception when attempting to run elevated code within a web part, and not obtaining an exception when the same code is run from within a list item event handler.
In both cases, I am performing the following steps:
1) Elevating to the SHAREPOINT\system account using SPSecurity.RunWithElevatedPrivileges
2) Opening a new SPSite using the site GUID of the list item I am going to modify, new SPSite(item.Web.Site.ID)
3) Opening a new SPWeb using the web GUID of the list item I am going to modify, Site.OpenWeb(item.Web.ID)
4) Opening a new instance of the list item, web.Lists[item.ParentList.ID].GetItemById(item.ID)
5) Breaking the security role inheritance of the new list item, newItem.BreakRoleInheritance
6) Updating the new list item, newItem.Update
When I perform the above steps from within a web part, I recieve the following exception: Microsoft.SharePoint.SPException: The security validation for this page is invalid.
When I perform the above steps from within an ItemUpdated event handler, I do not recieve an exception, and the requested operations are performed correctly.
Utilizing an event handler to call this code poses a serious issue. I must periodically update the permissions of the list item based on the value of several of the fields. Updating the role assignments for the item inside the ItemUpdated generates subsequent event-handler calls--which will eventually terminate in a save conflict exception.
Are there extra steps that I need to take when inside web part-based code to run elevated code as described above?
Thank you.
解答
- I know how you can work arround "Microsoft.SharePoint.SPException: The security validation for this page is invalid."

Just disable form digest validation for a little bit
Code SnippetSPWebApplication webApp = currentWeb.Site.WebApplication;
bool formDigestEnabledStatus = webApp.FormDigestSettings.Enabled;
webApp.FormDigestSettings.Enabled = false;
//Do stuff to BreakRoleInheritance here
webApp.FormDigestSettings.Enabled = formDigestEnabledStatus;
Although given the suggestions that others are making that my uncover other issues that their posts hopefully resolve
所有回覆
About the security validation: since i havent seen your code it might be a shot in the dark, but try and enable AllowUnsafeUpdates on the site (SPWeb) you are accessing:
myWeb.AllowUnsafeUpdates = true;
Regarding recursive event firing you can disable event firing while updating list item:
this.DisableEventFiring();
// do changes here// when changes is done use SystemUpdate(false);
// SystemUpdate wont change modified or modifiedBy fieldsyourListItem.SystemUpdate(false);
this.EnableEventFiring();
Additional reading:
http://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.speventreceiverbase_methods.aspx
hth
i have the same requirementas you do. I need to change the item's permission based on the value of fields (e.g. login name)
but i got the following error :
: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
- Tough to say what's causing the issue. You could try setting the CatchAccessDeniedException to False on the SPSite object.
I guess the problem is captured in the MS KB:
932056 (http://support.microsoft.com/kb/932056/) One or more custom programs do not finish successfully when you run multiple custom programs that use the BreakRoleInheritance function in the Windows SharePoint Services 3.0 object model
When i debug the program, run to BreakRoleInheritance function, it catches an exception and the function was not exectued. So the permission of the list item in Document Library cannot be updated.
Any one gets the same problem?
hi,
Has anybody solved the problem with the BreakRoleInheritance invoking?
Hi,
Same problem here, is there a solution/workaround?
have you tried impersonation (as the current user)?
string portalName; SPSite portal = SPControl.GetContextSite(this.Context); portalName = "http://" + portal.HostName + ":" + portal.Port.ToString();
System.Security.Principal.WindowsImpersonationContext wic = null; wic = System.Security.Principal.WindowsIdentity.GetCurrent().Impersonate();using (SPSite site = new SPSite(portalName))
{
string refSiteName = System.Configuration.ConfigurationSettings.AppSettings["RefSite"].ToString(); using (SPWeb refWeb = site.OpenWeb(refSiteName)){
try{
refWeb.AllowUnsafeUpdates = true;//do your thing
}
catch (Exception e){
log.Error(e.Message + "\n" + e.StackTrace);}
}
wic.Undo();}
Hi everyone, any update on this issue?
I have the same exception.
Impersonator im =
new Impersonator(_mossAdminName, _domain, _mossAdminPwd); try{
im.Impersonate();
try{
web.AllowUnsafeUpdates =
true;item.BreakRoleInheritance(
false); //item is a SPListItem or SPList}
catch{
}
}catch{}finally{im.undo();}
I only received this error in breaking document library and folder permission.
[date time] [Error]Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))
It's fine when breaking file's permission inheritance. Any idea?
I encountered two problems while trying to break the permission inheritance.
1. BreakRoleInheritance(false) throws an exception. I can find no solution, so my workaround is to call BreakRoleInheritance(true) and programmatically remove all permissions.
2. BreakRoleInheritance() sets AllowUnsafeUpdates to false. I set it back to true again.
Here's my working code:
Code Block// Run as system administrator.
SPSecurity.RunWithElevatedPrivileges(delegate(){
// Get current site collection. using (SPSite SiteCollection = new SPSite(SPControl.GetContextSite(System.Web.HttpContext.Current).ID)){
SiteCollection.AllowUnsafeUpdates =
true; // Not sure this is necessary SPWeb myWeb = SiteCollection.OpenWeb(...);myWeb.AllowUnsafeUpdates =
true; SPList myList = myWeb.Lists["ListName"]; // Remove all permissions. if (!myList.HasUniqueRoleAssignments){
// There's a bug in BreakRoleInheritance(). Doesn't work when you pass // 'false', so pass 'true' and manually delete all permissions.myList.BreakRoleInheritance(
true); // BreakRoleInheritance sets myWeb.AllowUnsafeUpdates back to false, // so put it back to true;myWeb.AllowUnsafeUpdates =
true;}
while (myList.RoleAssignments.Count > 0){
myList.RoleAssignments.Remove(0);
}
myList.Update();
}
});
hth,
Chris
Hi all,
My MS support info for everyone.
Problem Description:
===============
When you call SPList.BreakRoleInheritance(false) from an HTTP GET request, although you have specified SPWeb.AllUnsafeUpdates=true, you will still be thrown an exception
Updates are currently disallowed on GET requests. To allow updates on a GET, set the 'AllowUnsafeUpdates' property on SPWeb.
Cause:
=====
This is by design limitation of SPList.BreakRoleInheritance
BreakRoleInheritance does it work in two steps. First, it needs to revert its permission to have same permission settings as parent (this is a less expensive operation, and give the list a fresh start on its road to unique permission). Later it checks CopyRoleAssignments parameter. If it is false, it takes an extra step to clean up permission on the list. A side effect of step 1 is that it dirties some internal objects in SPWeb, and cause them to be recreated. Unfortunately, the re-creation of those internal objects cause SPWeb.AllowUnsafeUpdates to have a default value which is false. That is, SPWeb.AllowUnsafeUpdates is reset in middle of call to SPList.BreakRoleInheritance, therefore we got the exception.
Resolution:
========
There are two possible workarounds to the issue:
1. Call SPList.BreakRoleInheritance from a HTTP POST request. That is, we can first have a button on UI and have users to click. In response to users’ click, we call SPList.BreakRoleInheritance. There is a first HTTP GET request by which, SharePoint has a chance to embed some digest to validate requests on return (HTTP POST). Therefore, we no longer need to set SPWeb.AllowUnsafeUpdates=true. This is recommended approach from security perspective.
2. First call SPList.BreakRoleInheritance(true). Then, use custom code to clean up permission and create your own permission set for the list as needed. The sample code are:
SPWeb web = SPControl.GetContextWeb(this.Context);
SPListCollection lists = web.Lists;
//Guid docLibGuid = lists.Add("Doc Lib Sample 1", "Doc Lib Desc", SPListTemplateType.DocumentLibrary);
//SPList docLib = lists[docLibGuid];
SPList docLib = lists["Doc Lib Sample 1"];
//docLib.ParentWeb.AllowUnsafeUpdates = true;
docLib.BreakRoleInheritance(true); //Exception throw here when the parameters is "false"
web.AllowUnsafeUpdates = true;
SPRoleAssignmentCollection roleAssigns = docLib.RoleAssignments;
for (int i = roleAssigns.Count-1; i >= 0; i--)
{
roleAssigns.Remove(i);
}
- 已提議為解答David Lozzi Friday, 31 October, 2008 19:36
Thanks. Cris
It Worked Well.
I too was struck with this problem for long.
reg,
saroj
Thanks eddy.
Above solution worked out very well
- I know how you can work arround "Microsoft.SharePoint.SPException: The security validation for this page is invalid."

Just disable form digest validation for a little bit
Code SnippetSPWebApplication webApp = currentWeb.Site.WebApplication;
bool formDigestEnabledStatus = webApp.FormDigestSettings.Enabled;
webApp.FormDigestSettings.Enabled = false;
//Do stuff to BreakRoleInheritance here
webApp.FormDigestSettings.Enabled = formDigestEnabledStatus;
Although given the suggestions that others are making that my uncover other issues that their posts hopefully resolve

