Call SharePoint online REST API from azure API

1.7k views Asked by At

I have developed a Azure API protected with AAD , which is working fine, now I would like to call SharePoint online REST API from my Azure API ,my SharePoint online is using same active directory as my azure API.

For calling SP API i need access token to authenticate SharePoint I assume the access token which authenticated the Azure API would be same to call SharePoint API this is what I did :

  1. My Azure API is registered in azure active directory (which is automatically done which I made authentication on )

  2. I updated the Azure app's manifest.json to enable oauth2 implicit flow:

    "oauth2AllowImplicitFlow": true

  3. I granted the app access to "Read and write items and lists in all site collections" on behalf of the user (under delegated permissions) from the Azure AD app settings page ("permissions to other applications").

I tried to this code to get access token :

        string clientId = "xxxxxxxxxx";
        string appKey = xxxxxxxxxxx";
        string aadInstance = "https://login.microsoftonline.com";
        string tenant = "mydomain.onmicrosoft.com";
        string domain = "mydomain.onmicrosoft.com";
        string resource = "https://mydomain.sharepoint.com";

        AuthenticationResult result = null;

        ClientCredential clientCred = new ClientCredential(clientId, appKey);
        string authHeader = HttpContext.Current.Request.Headers["Authorization"];
        string userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim();
        UserAssertion userAssertion = new UserAssertion(userAccessToken);
        string authority = aadInstance + domain;
        AuthenticationContext authContext = new AuthenticationContext(authority);

        //result = await authContext.AcquireTokenAsync(resource, clientCred); // auth without user assertion (fails, app only not allowed)

        result = await authContext.AcquireTokenAsync(resource, clientCred, userAssertion); // clientCred and userAssertion params have swapped places since Kirk's blog
        return result.AccessToken;

but authHeader is null , I came across this question which mentions in order to retrieve a user token uses ADAL.js using authenticationContext.acquireToken(clientId), then include the resulting token in the header of the AJAX request to the WebAPI

I am not sure how i need to include this in my azure API anyway i appreciate any thoughts or idea to get access token to run SharePoint online APIs behalf of logged in user in azure API

0

There are 0 answers