I have a multi-tenant Azure AD web application set up. This represents a scheduled task that needs to get a list of Site Collections from each one of (the web app's) SharePoint Online Tenants.

I am trying to achieve this by using CSOM as detailed in this blog post from Sahil Malik.

The first step in the code in the blog post is a call to this method from the TokenHelper class:

public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
    string targetPrincipalName,
    string targetHost,
    string targetRealm)
  1. What should I put in place of the targetPrincipalName? Where do I obtain this value for each one of my tenants?

  2. Should my targetHost be the admin URL for each tenant? For example: "http://tenant1-admin.onmicrosoft.com/"?

  3. Should my 'targetRealm' be null?

Update: Having read through parts of the implementation of the GetAppOnlyAccessToken() method, I've realized I've been missing several appSettings that are required for it to work.

So far I've gathered the following but am still getting "(400) Token request failed." from SharePoint Online:

    <!-- Guid to the left of @ in App Identifier (?) -->
    <add key="ClientId" value="..." />
    <!-- Not sure how to obtain this as: -->
    <add key="ClientSecret" value="..." />
    <!-- Guid to the right of @ in App Identifier (?) -->
    <add key="Realm" value="..."/>

App Identifier shown in SharePoint Online appprincipals.aspx page

Am I missing any other appSettings? Am I correctly populating the ones above?

1 Answer 1


I'm answering my own question for future reference because I've been able to get the code working.

Would love to see (and will accept) a more detailed response.

Rather than use the identity of the Azure AD Web Application, I've started using the identity of a provider-hosted SharePoint Add-in. A part of my business solution is that each tenant will install this add-in anyway so it came in handy.

The code that worked for me:

var tenantAdminUri = new Uri("https://<tenant_name>-admin.sharepoint.com/");

var realm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri);

var token = TokenHelper.GetAppOnlyAccessToken(

And the following in app.config:

    <!-- Guid to the left of @ in App Identifier -->
    <add key="ClientId" value="..." />
    <!-- Obtained when SharePoint Add-in created -->
   <add key="ClientSecret" value="..." />

One important detail is to go into the SharePoint Add-in's AppManifest.xml and under the 'Permissions' tab to check the box that says "Allow the add-in to make app-only calls to SharePoint."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.