title: Application access to SharePoint Online using Azure AD Token
body: <p>How can I get an application token to query SharePoint with application credentials (= without user impersonation) using Azure AD?</p>
  
  <p>The following code works perfectly for querying data as a user but we need to fetch information without impersonation like listing all sites in the collection regardless of user permissions etc.</p>
  
  <p>Exception thrown:</p>
  
  <blockquote>
    <p>An exception of type
    'Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException'
    occurred in mscorlib.dll but was not handled in user code</p>
    
    <p>Additional information: AADSTS70001: Application with identifier 'xxx'
    was not found in the directory sharepoint.com</p>
  </blockquote>
  
  <p><strong>Code to get token:</strong></p>
  
  <pre><code>  internal static async Task&lt;string&gt; GetSharePointAccessToken(string url, string userAccessTokenForImpersonation)
              {
  
              string clientID = @"&lt;not posted on stack overflow&gt;";
              string clientSecret = @"&lt;not posted on stack overflow&gt;";
  
              var appCred = new ClientCredential(clientID, clientSecret);
              var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/common");
  
              // Use user assetion if provided, otherwise use principal account
              AuthenticationResult authResult = null;
  
              if (string.IsNullOrEmpty(userAccessTokenForImpersonation))
              {
                  authResult = await authContext.AcquireTokenAsync(new Uri(url).GetLeftPart(UriPartial.Authority), appCred);
              }
              else
              {
                  authResult = await authContext.AcquireTokenAsync(new Uri(url).GetLeftPart(UriPartial.Authority), appCred, new UserAssertion(userAccessTokenForImpersonation));
              }
  
              return authResult.AccessToken;
          }
  </code></pre>
  
  <p><strong>Test code:</strong></p>
  
  <pre><code>// Auth token from Bearer https://xxx.azurewebsites.net/.auth/me
  string authHeader = @"&lt;valid jwt bearer token from azure auth&gt;";
  var sharePointUrl = @"https://xxx.sharepoint.com/sites/testsite/";
  
  string sharePrincipalToken = await GetSharePointAccessToken(sharePointUrl, null); // &lt;-- doesn't work
  string sharePointUserToken = await GetSharePointAccessToken(sharePointUrl, authHeader); // &lt;-- works
  </code></pre>
  
  <p><strong>Permissions in Azure AD:</strong></p>
  
  <p><a href="https://i.stack.imgur.com/UV0Dm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UV0Dm.png" alt="Permissions in Azure AD"></a></p>