1

I've setup a Daemon application on a server to create a folder in a SharePoint server using MS Graph's Rest API. When I attempt to create a folder using axios.post(), I get a 401(Unauthorized) error but I am able to get information from the files using axios.get(). Both use the same "getToken()" method to get a token that is passed to the function that makes the request.

The getToken() method is below:

const msal = require("@azure/msal-node");
async function getToken() {
    try {
        //setup of the conditions for the acquisition of token
        const msalConfig = {
            auth: {
                clientId: process.env.CLIENT_ID,
                authority: process.env.AAD_ENDPOINT + process.env.TENANT_ID,
                clientSecret: process.env.CLIENT_SECRET
            },
            system: {
                loggerOptions: {
                    loggerCallback(loglevel, message, containsPii) {
                        console.log(message);
                    },
                    piiLoggingEnabled: false,
                    logLevel: msal.LogLevel.Verbose
                }
            }
        };
        const apiConfig = {
            uri: process.env.GRAPH_ENDPOINT + "v1.0/users"
        };
        const tokenRequest = {
            scopes: [process.env.GRAPH_ENDPOINT + ".default"]
        };
        const cca = new msal.ConfidentialClientApplication(msalConfig);

        //atempts the token acquisition
        const authResponse = await cca.acquireTokenByClientCredential(tokenRequest);
        //console.log("GetToken(). authResponse: ", authResponse.accessToken); // display access token
        return authResponse;
    } catch (error) {
        return error;
    }
}
const responces = await makeRequest(
`https://graph.microsoft.com/v1.0/groups/${process.env.Netsuite_File_Repository}/drive/items/${process.env.TestBuilder}/children`,
            authRes.accessToken,
            'post',//Get or Post methods
            {
                "name": "New Folder",
                "folder": {}
            },
        );

When The program is run in addition to the 401(Unauthorized) error I get this output:

'www-authenticate':
         'Bearer realm="", authorization_uri="https://login.microsoftonline.com/common/oauth2/authorize", client_id="00000003-0000-0000-c000-000000000000"'

I believe I have all of the relevant permissions that are needed to create a folder using the application.

A picture of permissions granted to the program, as well as Files.ReadWrite.All, Sites.ReadWright.All, and Directory.ReadWrite.All:

a picture of permissions granted to the program, as well as Files.ReadWrite.All, Sites.ReadWright.All, and Directory.ReadWrite.All

With some more digging I was able to get this error to show up:

{ code: 'InvalidAuthenticationToken',
  message: 'Access token is empty.',
  innerError:
   { date: '2021-10-14T16:00:32',
     'request-id': 'c4dc729b-3304-40df-b131-e13e7400ec3b',
     'client-request-id': 'c4dc729b-3304-40df-b131-e13e7400ec3b' } }

I've turned on logging for MSAl and I get the following:

[Thu, 14 Oct 2021 16:00:31 GMT] : @azure/[email protected] : Info - acquireTokenByClientCredential called
[Thu, 14 Oct 2021 16:00:31 GMT] : @azure/[email protected] : Verbose - initializeRequestScopes called
[Thu, 14 Oct 2021 16:00:31 GMT] : [Removed ID Info] : @azure/[email protected] : Verbose - buildOauthClientConfiguration called
[Thu, 14 Oct 2021 16:00:31 GMT] : [Removed ID Info] : @azure/[email protected] : Verbose - building oauth client configuration with the authority: https://login.microsoftonline.com/Removed ID Info
[Thu, 14 Oct 2021 16:00:31 GMT] : [Removed ID Info] : @azure/[email protected] : Verbose - createAuthority called
[Thu, 14 Oct 2021 16:00:32 GMT] : [Removed ID Info] : @azure/[email protected] : Verbose - Client credential client created
[Thu, 14 Oct 2021 16:00:32 GMT] : [Removed ID Info] : @azure/[email protected] : Verbose - No client info in response
1
  • Please provide the full error you get including the request id and timestamp. Also please explain how you are acquiring the access token used in both cases. You should also try these steps on postman and see if you get the error. Commented Oct 14, 2021 at 15:26

1 Answer 1

1

It turns out that the main issue I was having was caused by improper formatting in my request. Here is my updated request function below also I wasn't marking my request as "application/json" content:

async function makeRequest(endpoint, accessToken, methods, reqBody) {
//setup for axios()
let config = {
    method: methods,
    url: endpoint,
    headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${accessToken}`
    },
    data: JSON.stringify(reqBody)
};

//make the request using axios
axios(config)
    //act on the response, in this case, logging it to the terminal
    .then(function (response) {
        console.log(JSON.stringify(response.data));
        return response;
    })
    .catch(function (error) {
        console.log(error.response.data);
        return error;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.