This blog post is a contribution from Aaron Miao, an engineer with the SharePoint Developer Support team.
RunWithElevatedPrivileges executes the specified method with Full Control rights even if the user does not otherwise have Full Control. This is not true for User Profile API.
To reproduce, with code below in a web part:
If the user, regardless the user is farm administrator or site administrator or normal user, who runs the code is not in User Profile Service Application (UPA) Administrators and does not have “Manage Profiles” permission, the code will throw exception below:
Attempted to perform an unauthorized operation.
at Microsoft.Office.Server.UserProfiles.OrganizationProfileManager.CreateOrganizationProfile(ProfileSubtype subtype, ProfileBase parentProfile)
SharePoint requires a user or group to be added to Administrators for User Profile Service Application with “Manage Profiles” permission (shown below like test1) in order to peroform the task like above in code sample.
In case your business needs require users apart from Administrators for User Profile Service Application to be able to create organization profiles (not sure why you’d want that though), the workaround is to set HttpContext.Current to null like code below.
The workaround makes the service account of User Profile Service Application to execute the code. The service account should be in Administrators for User Profile Service Application with Full Control permission.
Setting Network Service as service account of User Profile Service Application may not work.