Skip to content

401 GraphError by getting emails #1534

Closed

Description

Bug Report

Prerequisites

  • [+] Can you reproduce the problem?
  • [+] Are you running the latest version?
  • [+] Are you reporting to the correct repository?
  • [+] Did you perform a cursory search?

Description

I am trying to get a list of emails using microsoft-graph-client. I got a refresh_token and configured App + secret. My App have Mail.Read permission

My code:
`const { Client } = require('@microsoft/microsoft-graph-client');
const dotenv = require('dotenv');

dotenv.config();

const clientId = process.env.OUTLOOK_CLIENT_ID;
const clientSecret = process.env.OUTLOOK_SECRET;
const tenantId = process.env.OUTLOOK_TENANT_ID;
const refreshToken = process.env.OUTLOOK_REFRESH_TOKEN;`

async function getAccessToken() {
try {
const url = 'https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token';
const params = new URLSearchParams();
params.append('grant_type', 'refresh_token');
params.append('client_id', clientId);
params.append('client_secret', clientSecret);
params.append('refresh_token', refreshToken);
params.append('scope', 'https://graph.microsoft.com/.default');

    const response = await fetch(url, {
        method: 'POST',
        body: params,
    });
    // console.log(response)

    const data = await response.json();
    return data.access_token;
} catch (error) {
    console.log(error)
}

}

async function getNewEmails(accessToken) {
try {
const client = Client.init({
authProvider: (done) => {
done(null, accessToken);
},
});

    const response = await client.api("/me/messages").top(10).get()

    return response.value;
} catch (error) {
    console.log(error)
}

}

(async () => {
try {
const accessToken = await getAccessToken();
const newEmails = await getNewEmails(accessToken);
console.log(newEmails);
} catch (error) {
console.log(error)
}
})();`

Console Errors:

GraphError
at new GraphError (D:\Tools\Bots\bot\node_modules@microsoft\microsoft-graph-client\lib\src\GraphError.js:34:28)
at Function. (D:\Tools\Bots\bot\node_modules@microsoft\microsoft-graph-client\lib\src\GraphErrorHandler.js:97:30)
at step (D:\Tools\Bots\bot\node_modules\tslib\tslib.js:193:27)
at Object.next (D:\Tools\Bots\bot\node_modules\tslib\tslib.js:174:57)
at D:\Tools\Bots\bot\node_modules\tslib\tslib.js:167:75
at new Promise ()
at Object.__awaiter (D:\Tools\Bots\bot\node_modules\tslib\tslib.js:163:16)
at GraphErrorHandler.getError (D:\Tools\Bots\bot\node_modules@microsoft\microsoft-graph-client\lib\src\GraphErrorHandler.js:87:24)
at GraphRequest. (D:\Tools\Bots\bot\node_modules@microsoft\microsoft-graph-client\lib\src\GraphRequest.js:315:84)
at step (D:\Tools\Bots\bot\node_modules\tslib\tslib.js:193:27) {
statusCode: 401,
code: null,
requestId: null,
date: 2023-11-14T18:18:41.708Z,
body: ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
}

I get an error at the moment of calling the "await client.api("/me/messages").top(10).get()" function

Steps to Reproduce

  1. Add and fill .env
  2. npm i @microsoft/microsoft-graph-client dotenv
  3. run the code

I checked access_token from "getAccessToken()" it does not come "undefined", I get everything right ( I think). So my main problem is with getting the emails. I understand that 401 means "Not authorized", but I don't understand how to fix it.

Usage Information

Request ID - Value of the null field if you are receiving a Graph API error response

SDK Version - 3.0.7

Node Version - v20.8.0

Activity

  1. sebastienlevert commented on Nov 14, 2023

    @sebastienlevert
    Contributor

    When calling /me/messages you need to provide the context of a user via a delegated token. It think here you are using an application permission that will give you an application token. To run the way you are describing it, you'll need to use a specific user id, for instance /users/{userId}/messages.

    https://learn.microsoft.com/en-us/graph/api/user-list-messages?view=graph-rest-1.0&tabs=http#http-request

  2. SamuiRo commented on Nov 15, 2023

    @SamuiRo
    Author

    When calling /me/messages you need to provide the context of a user via a delegated token. It think here you are using an application permission that will give you an application token. To run the way you are describing it, you'll need to use a specific user id, for instance /users/{userId}/messages.

    https://learn.microsoft.com/en-us/graph/api/user-list-messages?view=graph-rest-1.0&tabs=http#http-request

    Thank you, that solved the problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions