azure-active-directorymicrosoft-graph-apiadaladal.jsmicrosoft-graph-sdks

microsoft-graph-client throws '#<GraphError>' error on API call


I would like to consume the Graph API from my Node backend. First I get an access token from adal-node by calling the acquireTokenWithClientCredentials method. So my token response would be

token response

I install the @microsoft/microsoft-graph-client package and tried to follow the guide from here https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/samples/node/main.js . For the isomorphic-fetch import I installed the isomorphic-fetch package.

async function bootstrap() {
  // ...
  const session: TokenResponse = await authenticationService.getSession(); // call the 'acquireTokenWithClientCredentials' function

  const client: Client = Client.init({
    authProvider: (done) => {
      done(null, session.accessToken);
    },
  });

  try {
    await client.api('/me').get();
  } catch (error) {
    throw error;
  }
}

The API call throws an exception. But I can't figure out what's wrong because the error only logs

(node:20561) UnhandledPromiseRejectionWarning: #<GraphError>

What is wrong or missing? Please let me know if you need more information. But I hope that my description should be enough for reproduction :) Thanks in advance.


Update

The application does not sign in as a user and should run as a background service. So maybe I can't access /me because the application is not a user. But when I update /me to /users (this endpoint should work) then I still get the same error.

So my current access token when accessing /users is

enter image description here


Solution

  • You can not use Client credential flow to get access token for /me endpoint. You should use auth code flow(acquireTokenWithAuthorizationCode) instead. Then you can call /me for the signed-in user.

    If you must use client credential flow, you should call /users/{id | userPrincipalName} for a specific user.

    Besides, if you want to call Microsoft Graph API, the value of resource which you used to get access token should be https://graph.microsoft.com.

    var resource = 'https://graph.microsoft.com';