Impersonation does not work with UserProfileManager
I am back after a long time and will now try to be a little more regular with my posts.
Recently we worked upon a curious problem. We were using UserProfileManager in a web part and wanted to get to the private properties of a user profile. Now as the web part would be available on the SharePoint site and not every user would have permissions to view the private properties of the profile, we decided to use SPSecurity.RunWithElevatedPrivileges. To get the private properties of a user profile, we need to use the following overloaded constructor of the UserProfileManager class:
The second “Boolean” parameter specifies whether to ignore user profile privacy policies. Now to set this parameter to “True” and see the private properties of the profile, the calling user should have explicit permissions as defined in the Central Administration site under SSP –> “User Profiles and My Sites” –> “Personalization services permissions”
You have to make sure that the user have “Manage User Profiles” permission.
Now my concern was, when I am using RunWithElevatedPrivileges and already running with System Account rights, why I was getting error:
User must have manage user profiles administrator rights to use administrator mode
Funny enough, when I was calling the User Profile Web Service (_vti_bin/userprofileservice.asmx), the same code was working perfectly fine and no error cropped up.
This lead me to dig deeper into the belly of the beast to see what is going under the hoods. After tracing back the calls and digging into the code, finally discovered that SharePoint was using HttpContext.Current.User.Identity which gives the User security for the current HTTP request (more details in http://msdn.microsoft.com/en-us/library/aa480475.aspx) instead of calling System.Security.Principal.WindowsIdentity.GetCurrent() which would actually represent the impersonated user.
Now comes, why it is working when we are using the User Profile WebService call?
As we were already initiating the the web service request using the impersonated identity of Application Pool, the ASP.net request was being started by App Pool identity, which in-turn had the full permissions. That’s the reason why the web service calls works while the Object Model call from a Windows Application failed.
So in effect, you cannot impersonate a user and try to get the private properties of a user profile. You would need to give explicit permissions to every user who wants to access the private properties of the User Profiles stored in SharePoint.
Use SharePoint’s UserProfile web service call within the impersonated context to get the data.
Hope that helps out some of you…