Don’t you hate when you make dumb – and upon later inspection, rather obvious – mistakes?
I was struggling (I’m too embarrassed to tell you how many hours) with the fact that even though I had broken permission inheritance, my code was always saying that the Current User had access to the list item – and full access at that (that should have been my first clue).
bool hasPermissions = false;
try
{
//http://blogs.msdn.com/b/ryanrogers/archive/2004/07/15/184594.aspx
site.CatchAccessDeniedException = false;
hasPermissions = item.DoesUserHavePermissions(SPBasePermissions.ViewListItems);
}
catch (Exception ex2)
{
hasPermissions = false;
}
finally
{
site.CatchAccessDeniedException = true;
}
if (!hasPermissions)
{
ShowError("User does not have permissions to list item");
return;
}
So I thought the above code would work. From everything I could see on the web, it SHOULD have worked. So why didn’t it?
Turns out that I was running in Elevated Privileges mode, so the “Current User” was the system account. Now mind you, that code above was NOT inside that Elevated Privileges wrapper – that’s what threw me I think. But, what I did do (and I’m questioning now WHY did I do it this way) is that I had an SPWeb object variable that I set inside the RunWithElevatedPrivillges method.
SPList list = null;
SPWeb web = null;
SPSite site = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite secureSite = new SPSite(webURL))
{
site = secureSite;
using (SPWeb secureWeb = secureSite.OpenWeb())
{
web = secureWeb;
}
}
});
}
catch
{
ShowError("Could not retrieve web at '" + webURL + "'");
return;
}
try
{
list = web.Lists[listID];
}
catch
{
ShowError("List ID '" + strListID + "' not found in web");
return;
}
try
{
SPListItem item = list.GetItemById(itemID);
So apparently the web object stayed elevated, thus the list was elevated, thus the List Item was elevated. All I had to do was use the overload of the DoesUserHavePermissions method. But that being said, I’m rethinking this whole, “pull it out of the elevated wrapper” thing I have going on here. I’m marking this post as “Best Practices” as in what NOT to do
.
hasPermissions = item.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser, SPBasePermissions.ViewListItems);
