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).
When using DoesUserHavePermissions() method on a securable object, you get UnauthorizedAccessException.
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.
I managed to solve this issue by explicitly opening the securable object with a System Account token, instead of using RunWithElevatedPrivileges.
SPSite site = <span style="color: #008000">// get your normal reference for the SPSite/SPWeb/SPLIstItem object;</span><br />SPSite elevSite = <span style="color: #0000ff">new</span> SPSite(site.ID, SPContext.Current.Site.SystemAccount.UserToken);<br /><span style="color: #0000ff">bool</span> hasPermissions = elevSite.DoesUserHavePermissions(arbitraryUser, arbitraryPermission);<br />