1
votes

I am a newbie to Microsoft Graph API and I am trying to access One Drive through a NodeJS API. I have done the following to get the Access Token from the Graph API in order to access my One Drive without the user has to log in every time they want to access something on my drive.

const postData = {
  client_id: 'xxxxxxxxxxxxxxxxxxx',
  scope: 'https://graph.microsoft.com/.default',
  client_secret: 'xxxxxxxxxxxxxxxxxxx',
  grant_type: 'client_credentials'
};

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// Get  access token and assign it to the token variable
axios
  .post('https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxx/oauth2/v2.0/token', qs.stringify(postData))
  .then(response => {
    token = response.data.access_token;
  }).catch(error => {
    console.log(error);
  });

My API is successfully getting the token. However, I am getting errors when I try to access my One Drive using this token with the endpoint that is given on the documentation. The code is as follows:

const AuthStr = 'Bearer ' + token;

axios.get('https://graph.microsoft.com/v1.0/drive/root/children', { headers: { Authorization: AuthStr } }).then(response => {
    console.log(response);
}).catch((error) => {
    console.log(error);
});

What am I doing wrong?

1
Could you please share the error message ? - Hury Shen
It seems you need to specify the drive id or add me in the url, such as https://graph.microsoft.com/v1.0/me/drive/root/children. - Hury Shen
Error: Request failed with status code 401 at createError (/Users/shafkhan/Documents/Experiments/GraphAPI/node_modules/axios/lib/core/createError.js:16:15) at settle (/Users/shafkhan/Documents/Experiments/GraphAPI/node_modules/axios/lib/core/settle.js:17:12) at IncomingMessage.handleStreamEnd (/Users/shafkhan/Documents/Experiments/GraphAPI/node_modules/axios/lib/adapters/http.js:244:11) at IncomingMessage.emit (events.js:322:22) at endReadableNT (_stream_readable.js:1187:12) at processTicksAndRejections (internal/process/task_queues.js:84:21) { - Shafkhan
401 error is related to the permission. Did you add the permission to the registered app in your ad ? - Hury Shen
If you use the /me endpoint List children in the root of the current user's drive, then you should not use the client credential flow. For the /me endpoint it usually requires the user to log in, so you should use the auth code flow docs.microsoft.com/en-us/azure/active-directory/develop/…, and then The application grants delegated permissions. I think your problem is not lack of permissions, but the wrong authorization method. You are using the wrong token to call the api. - Carl Zhao

1 Answers

1
votes

You just need to use the url as below:

https://graph.microsoft.com/v1.0/users/{userid}/drive/root/children

Specify the user id in the url because the access token of client_credentials grant flow doesn't contain user identity.