Share via


Adding Site Collection Admin in CSOM in a SharePoint 2013 App

My Microsoft Consulting Services buddy (David Weinstein) and I couldn’t find any documentation on adding a Site Collection Administrator in SharePoint 2013.  I thought I would try to remedy that.

When looking at our documentation I noticed a comment stating that this doesn’t work.  At first, I thought maybe the commenter was accurate.  When first trying to execute this code, I was greeted with this:

SNAGHTML148d6cc

Notice the part I highlighted in red.  You need to be a site collection administrator to set this property.  At this point I was scratching my head thinking “I am a site collection administrator!”.  Then I remembered that I had to request permissions.  So I made my app manifest look like this:

SNAGHTML14d6fdd

I had to request the FullControl permission at the “Site Collection” scope.  After doing this and remembering the Update() method on my SP.User object, the code worked successfully.

Note that you do have to already be a site collection administrator to add one.

Here is the code.

User spUser = null;

var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
spUser = clientContext.Web.EnsureUser("username@domain.com or DOMAIN\LoginName");
spUser.IsSiteAdmin = true;
spUser.Update();

        clientContext.Load(spUser);
        clientContext.ExecuteQuery();

ViewBag.UserName = spUser.Title;
}
}

Comments

  • Anonymous
    April 01, 2014
    How can the same thing be achieved by PowerShell (or anyway using CSOM) that does not have the ability to set the permission level? If the user running the CSOM is a farm administrator they cannot still add a Site Collection Administrator