Reputation: 1221
I'm receiving an error when my code attempts to iterate through the SPListItems.RoleAssignments
collection in my event receiver. But only for users who have contributor rights. Users who have administrator rights.
I've tried the following:
Windows Impersation using the following code:
WindowsImpersonationContext ctx = null;
ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);
SPUserToken oSysToken = GetSysToken(properties.SiteId)
private static SPUserToken GetSysToken(Guid SPSiteID)
{
SPUserToken sysToken = null;
using(SPSite oSite = new SPSite(SPSiteID))
{
sysToken = oSite.SystemAccount.UserToken;
}
if (sysToken == null)
{
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using(SPSite site = new SPSite(SPSiteID))
{
sysToken = site.SystemAccount.UserToken;
}
});
}
return sysToken;
}
Finally I've tried SPWeb.AllowUnsafeUpdates = true;
I've try all method seperatly and collective together and nothing. It seems like its through an exception as well on SPListItems.RoleAssignments.Count
.
Upvotes: 3
Views: 6951
Reputation: 14880
Users need at least Manage Permissions rights on the object to read and modify the SPSecurableObject.RoleAssignments
.
In order to execute code with system account (elevated) privileges on a SharePoint object you have to "re-open the given object":
SPListItem item = // the item from the event receiver
// Re-open the item with the system account
using (SPSite adminSite = new SPSite(item.Web.Url, SPUserToken.SystemAccount))
{
using (SPWeb adminWeb = adminSite.OpenWeb())
{
SPListItem adminItem = adminWeb
.Lists[item.ParentList.ID]
.GetItemByUniqueId(i.UniqueId);
// execute your code with the system account on the item.
// adminItem.RoleAssignments.WhatEver
}
}
Please note the use of SPUserToken.SystemAccount
. This makes the "System Account Token" hack required in SharePoint 2007 obsolete.
For actions on SharePoint objects SPSecurity.RunWithElevatedPrivileges
or WindowsIdentity.Impersonate(System.IntPtr.Zero)
is not required.
I've written a blog post that covers this topic: How To Open a SPSite With thw System Account In SharePoint 2010.
Upvotes: 4