Search code examples
node.jsaxiosmicrosoft-graph-api

Nodejs Microsoft Upload File to a Sharepoint file storage API


Hey i am trying to upload a file to a sharepoint file storage for that i want to find out all available sites and their id.

const axios = require('axios');

module.exports = async function getSiteIds(logger, accessToken) {
    const graphEndpoint = 'https://graph.microsoft.com/v1.0/sites?search=*';
    const headers = {
        Authorization: `Bearer ${accessToken}`,
    };

    try {
        const response = await axios.get(graphEndpoint, { headers });
        const siteIds = response.data.value.map(function(site) {
            return site.id;
        });
        return siteIds;
    } catch (error) {
        logger.error('Error getting site IDs:', error.message);


        throw error;
    }
}

when i am doing this i get an error:

'AccessDenied',
message: 'Either scp or roles claim need to be present in the token.',

i am generating a token with scope '.default'

I was execting a list of all sharepoint sites. My application has all needed permissions...


Solution

  • const msalConfig = {
      auth: {
        clientId: 'your_client_id',
        authority: 'https://login.microsoftonline.com/your_tenant_id',
        
      }
    };
    
    const request = {
      scopes: ['Sites.Read.All', 'Sites.ReadWrite.All']
    };
    
    const myMSALObj = new Msal.UserAgentApplication(msalConfig);
    
    async function getSiteIds(logger) {
      try {
        const loginResponse = await myMSALObj.loginPopup(request);
        const accessToken = loginResponse.accessToken;
    
        const graphEndpoint = 'https://graph.microsoft.com/v1.0/sites?search=*';
        const headers = {
          Authorization: `Bearer ${accessToken}`,
        };
    
        const response = await axios.get(graphEndpoint, { headers });
        const siteIds = response.data.value.map(site => site.id);
        return siteIds;
      } catch (error) {
        logger.error('Error getting site IDs:', error.message);
        throw error;
      }
    }
    
    module.exports = getSiteIds;