Microsoft-Graph API returning HTTP 403 - Forbidden on NodeJS Daemon Quickstart application

Tony Lockhart 106 Reputation points
2022-02-27T04:19:47.28+00:00

I just created a tenant in Azure. The directory has an office 365 Business Standard License. I have downloaded the Node Daemon quick-start application and updated the clientID, TenantId, secret, etc in the .env file, as the instructions direct. However, I am receiving 403 Error when running the getUser MS-Graph query. Before downloading the sample code, step 3 indicates Admin consent is insufficient (see screenshot below). However, I am the owner, and I have granted admin consent to all app-permissions (see screenshot 2). Is there another admin consent that needs to be granted?

178162-screen-shot-2022-02-26-at-105228-pm.png

178097-screen-shot-2022-02-26-at-110654-pm.png

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,273 questions
0 comments No comments
{count} votes

Accepted answer
  1. CarlZhao-MSFT 42,451 Reputation points
    2022-02-28T01:30:03.007+00:00

    Hi @Tony Lockhart

    This is an expected error, since you are using an unattended daemon, you should use application permissions.

    178210-test.png


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Abdul Gani 0 Reputation points
    2023-02-23T06:33:32.53+00:00

    Hi All,

    I have same issue (got 403 forbidden) when access microsoft graph with url:

    v1.0/users/<email sender>/sendMail
    

    and this is my msal-node method:

    import * as msal from "@azure/msal-node";
    //import static config
    import {
      TENANT_ID,
      CLIENT_ID,
      CLIENT_SECRET,
      AAD_ENDPOINT,
      GRAPH_ENDPOINT,
    } from "@config/email.config";
    //configurasi object untuk dapat melewati proses instanciate MSAL
    const msalConfig: { auth: msal.NodeAuthOptions } = {
      auth: {
        clientId: CLIENT_ID,
        authority: AAD_ENDPOINT + "/" + TENANT_ID,
        clientSecret: CLIENT_SECRET,
      },
    };
    //interface untuk token request
    interface tokenRequestIface {
      scopes: string[];
    }
    //Dalam alur credential klien, izin perlu diberikan di portal oleh administrator penyewa.
    //izin dalam hal ini ditentukan oleh scope seperti dibawah
    const tokenRequest: tokenRequestIface = {
      scopes: [GRAPH_ENDPOINT + "/.default"],
    };
    //definisikan api graph microsoft endpoint url
    const apiConfig: { uri: string } = {
      uri: GRAPH_ENDPOINT + "/v1.0/users",
    };
    //inisiasi sebuah confidential aplikasi client
    const cca = new msal.ConfidentialClientApplication(msalConfig);
    //buat fungsi untuk mendapatkan token
    async function getToken(tokenRequest: tokenRequestIface) {
      return await cca.acquireTokenByClientCredential(tokenRequest);
    }
    export { apiConfig, tokenRequest, getToken };
    

    and then i use getToken above to get bearer token for http request to microsoft graph api:

    try {
        const tokenInfo = await getToken(tokenRequest);
        const mail = {
          subject: "Microsoft Graph JavaScript Sample",
          //This "from" is optional if you want to send from group email. For this you need to give permissions in that group to send emails from it.
          from: {
            emailAddress: {
              address: "yy@microsoft.com",
            },
          },
          toRecipients: [
            {
              emailAddress: {
                address: "xx@microsoft.com",
              },
            },
          ],
          body: {
            content:
              "<h1>MicrosoftGraph JavaScript Sample</h1>This is the email body",
            contentType: "html",
          },
        };
        const emailSentResponse = await callAPI({
          url: "v1.0/users/yy@microsoft.com/sendMail",
          accessToken: tokenInfo?.accessToken,
          method: "post",
          body: { message: mail, saveToSentItems: false },
        });
        res.send(emailSentResponse);
      } catch (error: any) {
        console.log("error send email", error);
        const statusCode: number | undefined = error.response?.status;
        if (statusCode) {
          return res.status(statusCode).send(error);
        }
        res.status(500).send(error);
      }
    

    after finish all code, i hit through postman and get 403 like this:

    {
        "message": "Request failed with status code 403",
        "name": "AxiosError",
        "stack": "AxiosError: Request failed with status code 403\n    at settle (/Users/fhi-it-dev/Documents/email-SMS-API/node_modules/axios/lib/core/settle.js:19:12)\n    at Unzip.handleStreamEnd (/Users/fhi-it-dev/Documents/email-SMS-API/node_modules/axios/lib/adapters/http.js:548:11)\n    at Unzip.emit (node:events:525:35)\n    at Unzip.emit (node:domain:489:12)\n    at endReadableNT (node:internal/streams/readable:1358:12)\n    at processTicksAndRejections (node:internal/process/task_queues:83:21)",
        "config": {
            "transitional": {
                "silentJSONParsing": true,
                "forcedJSONParsing": true,
                "clarifyTimeoutError": false
            },
            "adapter": [
                "xhr",
                "http"
            ],
            "transformRequest": [
                null
            ],
            "transformResponse": [
                null
            ],
            "timeout": 0,
            "xsrfCookieName": "XSRF-TOKEN",
            "xsrfHeaderName": "X-XSRF-TOKEN",
            "maxContentLength": -1,
            "maxBodyLength": -1,
            "env": {
                "Blob": null
            },
            "headers": {
                "Accept": "application/json, text/plain, */*",
                "Content-Type": "application/json",
                "Authorization": "Bearer xxxxxxxxxxxxxx",
                "User-Agent": "axios/1.3.3",
                "Content-Length": "343",
                "Accept-Encoding": "gzip, compress, deflate, br"
            },
            "baseURL": "https://graph.microsoft.com",
            "method": "post",
            "data": "{\"message\":{\"subject\":\"Microsoft Graph JavaScript Sample\",\"from\":{\"emailAddress\":{\"address\":\"yyy@fullertonhealth.com\"}},\"toRecipients\":[{\"emailAddress\":{\"address\":\"xxx@fullertonhealth.com\"}}],\"body\":{\"content\":\"<h1>MicrosoftGraph JavaScript Sample</h1>This is the email body\",\"contentType\":\"html\"}},\"saveToSentItems\":false}",
            "url": "v1.0/users/yyy@fullertonhealth.com/sendMail"
        },
        "code": "ERR_BAD_REQUEST",
        "status": 403
    }
    

    Please help, all setting already ok, (enable email, and also applications permissions like above....

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.