Sunday, November 9, 2008

Double hop resolution - the SharePoint way

Is there anything special about Double Hop issue in SharePoint site? Answer is no. Its the same old classic issue of IIS Website, with impersonation set to True issuing calls to different server, loosing the caller identity.

Classic resolution was to use RevertToSelf API ( its an unmanaged Win32 API). Turns off impersonation, Thread switches over to App pool account, does the work, once completed switches back to user account. Neat job done and not much frills.

Revertoself solution

[DllImport("advapi32.dll")]

static extern bool RevertToSelf();


WindowsIdentity endUser = WindowsIdentity.GetCurrent();
RevertToSelf();


// NOW THREAD IS RUNNING IN APP POOL ACCOUNT. Do whatever you need


WindowsImpersonationContext objContext = endUser.Impersonate();

The same could be used in your sharepoint code, however couple of not-so-comfy-things about this approach
- Usage of Win32 APIs in your code and (referring the dlls)
- Changing to ThreadAccount and back to user - anything can happen in between and you need careful with your exception handling to restore the thread identity. Any miss here, you rest of the code is going to run with elevated privileges.

Alternate option? SPElevated Privileges. As name indicates it changes SharePoint context for higher privileges. And behind the scenes, the API also does thread account swithcing to app pool account. We can leverage this fact for our problem.

The revised code would look like this. No unmanaged code, ensured revert whatever happens. Safe and sound approach.

SPSecurity.RunWithElevatedPrivileges(delegate()


{ // DO YOUR WORK HERE


}


);




As stated above, however note that SPElevated Privileges does more than just thread context switching. If in the block you have any Sharepoint related code, such as SPSite, SPWeb creation etc, they would be done with higher privileges which you may not want. Hence restrict the Using block size to only the statements which would require impersonation to be turned off temporarily.

No comments: