RunWithElevatedPrivileges does not work with UserProfile API
Published May 01 2019 03:33 PM 526 Views

First published on TECHNET on Nov 02, 2012

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:

	using (SPSite site = new SPSite("http://yourserver/")) 
			SPServiceContext context = SPServiceContext.GetContext(site); 
			ProfileSubtypeManager psm = ProfileSubtypeManager.Get(context); 
			string subtypeName = ProfileSubtypeManager.GetDefaultProfileName(ProfileType.Organization); 
			ProfileSubtype subType = psm.GetProfileSubtype(subtypeName); 
			OrganizationProfileManager opm = new OrganizationProfileManager(context); 
			OrganizationProfile parentOrg = opm.RootOrganization; 
			OrganizationProfile profile = opm.CreateOrganizationProfile(subType, parentOrg); // Requires privileges 
			profile.DisplayName = "Test Group " + DateTime.Now.ToString("MMMM dd H mm ss"); 
			UserProfileManager upm = new UserProfileManager(context); 
			UserProfile userProfile = upm.GetUserProfile(true); 
			profile.AddMember(userProfile.RecordId, OrganizationMembershipType.Leader); 
		catch(Exception ex) 
			string err = ex.StackTrace; 

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)
at UserProfileTestWP.UPATestWebPart.UPATestWebPart.<btn_Click>b__0()

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.

  HttpContext httpCtx = HttpContext.Current; 
  HttpContext.Current = null; 
  using (SPSite site = new SPSite("http://yourserver/")) 
    // code omitted here 
  } // end of using 

HttpContext.Current = httpCtx;


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.

Version history
Last update:
‎Sep 01 2020 03:46 PM
Updated by: