Search code examples
azure-active-directorymicrosoft-graph-apionedriveazure-ad-graph-api

Interact with OneDrive through Microsoft Graph API using Access Token


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?


Solution

  • 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.