0
votes

How can I get an application token to query SharePoint with application credentials (= without user impersonation) using Azure AD?

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.

Exception thrown:

An exception of type 'Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException' occurred in mscorlib.dll but was not handled in user code

Additional information: AADSTS70001: Application with identifier 'xxx' was not found in the directory sharepoint.com

Code to get token:

  internal static async Task<string> GetSharePointAccessToken(string url, string userAccessTokenForImpersonation)
            {

            string clientID = @"<not posted on stack overflow>";
            string clientSecret = @"<not posted on stack overflow>";

            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;
        }

Test code:

// Auth token from Bearer https://xxx.azurewebsites.net/.auth/me
string authHeader = @"<valid jwt bearer token from azure auth>";
var sharePointUrl = @"https://xxx.sharepoint.com/sites/testsite/";

string sharePrincipalToken = await GetSharePointAccessToken(sharePointUrl, null); // <-- doesn't work
string sharePointUserToken = await GetSharePointAccessToken(sharePointUrl, authHeader); // <-- works

Permissions in Azure AD:

Permissions in Azure AD

1

1 Answers

0
votes

The error message you are getting implies that you are signing in with a user that is pointing our token service to get a token in the context of "sharepoint.com"

This is because you are using the "common" endpoint. Read more about that here.

Instead try using a fixed endpoint, where the tenant is the same as where the application is registered and see if that solves your issue.

If your plan is to make this application accessible by multiple tenants, make sure that you have explicitly set your application to be multi-tenant, and then make sure you have a user from the external tenant try and sign into the application before you try doing service to service calls.

Let me know if this helps.