Checking for User Permissions and Getting UnauthorizedAccessException
August 18, 2014
In a recent project I have been writing code to check if an arbitrary user can create new documents in certain document libraries. In order to do the check, I used the good old DoesUserHavePermissions method, which is present in SPWeb, SPList and SPListItem objects (securable objects).
SYMPTOMS
When using DoesUserHavePermissions() method on a securable object, you get UnauthorizedAccessException.
CAUSES
There are multiple causes for this behavior.
FIrst, the current user context is such that the current user has no rights to enumerate permissions on the SPWeb/SPList/SPListItem object. If so, the exception will be raised.
So, your first inclination is to use RunWithElevatedPrivileges to check the permissions. However, it also throws the same exception. The cause is a token check that the DoesUserHavePermissions method includes in its code (as explained by Phil Harding). The user token is compared against the current user. Somehow, the user token for elevated object is not the same as the current user in the context and the exception is being thrown.
SOLUTION
I managed to solve this issue by explicitly opening the securable object with a System Account token, instead of using RunWithElevatedPrivileges.
SPSite site = // get your normal reference for the SPSite/SPWeb/SPLIstItem object;
SPSite elevSite = new SPSite(site.ID, SPContext.Current.Site.SystemAccount.UserToken);
bool hasPermissions = elevSite.DoesUserHavePermissions(arbitraryUser, arbitraryPermission);