How to add an administrator to OneDrive for Business?

Sometimes as an Office 365 global or SharePoint Service administrator, we need to access another user’s personal site (OneDrive for Business). Is that possible?  Yeah! We have several ways to add an administrator to OneDrive For Business!

  • By means of the Office 365 Admin Center
  • By using the SharePoint Online (SPO) User profiles service settings in the SPO Admin Center
  • By means of PowerShell using SPO cmdlets
  • By means of PowerShell using SPO Client Side Object Model (CSOM)

Adding an administrator to User’s personal site from the Office 365 Admin Center

Firstly we need to sign in the Office 365 admin center and navigate to “Users” section. Click the user that you want to add administrator to its personal site, scroll down to “OneDrive Settings”.

By clicking the “Access files”, you would be the administrator of that personal site.

Adding an administrator to User’s personal site from the SPO Admin Center

In fact, as a separated and complete service, SharePoint online does provide the same feature in its admin center. That means we can approach the goal by configuring  some settings in the SharePoint admin center.

For this method, we need to browse to the SharePoint admin center and navigate to “user profiles” section.

Click “manage user profile”, this will direct us to a query page.

Search the targeted user and right-click the corresponding item. “Manage Personal Site” will directly grant you the admin permission of the target site while “Manage site collection owners” will popup a wizard page:

The users in the “Site Collection Administrators” column will be able to access the personal site.

Adding an administrator to User’s personal site Using SPO Cmdlets

This approach is recommended as it only requires one cmdlet provided by SPO originally.

Set-SPOUser -Site $OneDriveSite -LoginName $AdminUser -IsSiteCollectionAdmin $true

Before we use this cmdlet, we’d better to have a overview on How to connect to SharePoint online using PowerShell.

Adding an administrator to User’s personal site Using CSOM

Last but not least, if we want to make this configuration automatic/programmable, is that possible? The answer is YES!  We can use CSOM.

ClientContext ctx = new ClientContext("https://{tenant}-admin.sharepoint.com"); 
var username = "Givename@{tenant}.onmicrosoft.com"; 

string palintext = @"i am password"; 
SecureString password = new SecureString(); 
char[] pass = palintext.ToCharArray(); for (int i = 0; 
i < pass.Length; i++) { password.AppendChar(pass[i]); } 

ctx.Credentials = new SharePointOnlineCredentials(username, password); 
var tenant = new Tenant(ctx); 
User spoUser = ctx.Web.CurrentUser; ctx.Load(spoUser); 
ctx.ExecuteQuery(); 

//Set the last parameter to false if you want to remove the user from the site collection admins 
tenant.SetSiteAdmin(onedriveUrl, spoUser.LoginName, true); 
ctx.ExecuteQuery();

The above code references the package Microsoft.SharePointOnline.CSOM and it uses user credential to authenticate the current user. We can check the results by browsing to the destination OneDrive For Business, Site collection administrators should already include the user through the code you just added.

One more

Nowadays more and more MS Services are migrating to use OAuth token instead of user credential (username+password) to authenticate users. Is that possible we take advantage of CSOM with OAuth token? The answer is yes! CSOM does accept either token or credential.

We do not need to fill out the “Credentials” property. instead, we attach a delegate to ClientContext. The delegate will internally append a token to each web request when ClientContext acquires data from the server.

Old
clientcontext.Credentials = new SharePointOnlineCredentials(username, password);
New
clientcontext.ExecutingWebRequest += Ctx_ExecutingWebRequest;
void Ctx_ExecutingWebRequest(object sender, WebRequestEventArgs e)
{
 e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + "AccessToken";
}

But how can we acquire the access_token? Here i mainly make use of the existing Authentication SDK: ADAL which is strongly recommended by MS. Of course you can implement your own method to get through the authentication procedure such as using httpclient. 

Below is my code, it’s suit for native application but can be used for web application with a little modification.

private async Task<AuthenticationResult> GetAccessToken()
{
  AuthenticationResult ar = null;
  AuthenticationContext AuthContext = new AuthenticationContext(authority, new FileCache());

  try
  {
    ar = await AuthContext.AcquireTokenSilentAsync(resourceid, clientid);
  }
  catch (AdalException ex)
  {
     // There is no access token in the cache, so prompt the user to sign-in.
    if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
    {
      Console.WriteLine("fail to acquire token silently"+ex.Message);
    }
    else
    {
      // An unexpected error occurred.
      Console.WriteLine(ex.Message);
    }
  }

  if (ar == null)
  {
    try
    {
      ar = await AuthContext.AcquireTokenAsync(resourceid, clientid, redirectUri, new PlatformParameters(PromptBehavior.Always));
    }
    catch (Exception acquireEx)
    {
      //utter failure here, we need let the user know we just can’t do it
      Console.WriteLine("fail to get token even though with user interaction"+acquireEx.Message);
    }
  }
  return ar;
}

Conclusion

Now we at least have 4 approaches to achieve the goal of accessing other user’s OneDrive For Business. The last method makes great sense and should be paid more attention. If you have anything unclear regarding this blog, please feel free to contact our team:

Leave a Reply

Your email address will not be published. Required fields are marked *