租户 GUID 的租户不存在。 Microsoft Graph API 与 Nodejs

问题描述 投票:0回答:1

我想动态读取给定电子邮件帐户的电子邮件,但遇到错误消息:“租户 GUID 的租户不存在”。我该如何解决这个问题?

错误信息

"error": {
   "code": "OrganizationFromTenantGuidNotFound",
   "message": "The tenant for tenant guid '24f192b9-85d3-4710-859a-d0806xxxxxxx' does not exist.",
   "innerError": {
   "oAuthEventOperationId": "8de2a75d-8df8-4a92-935e-660d3a102c5f",
   "oAuthEventcV": "X3bGiYtMYExtlEcJ5dVwWg.1.1",
    "errorUrl": "https://aka.ms/autherrors#error-InvalidTenant",
        "requestId": "042ee1f5-40d0-4936-ae12-79b9bb7bcf23",
        "date": "2024-12-19T08:56:58"
       }
   }

auth.js

import * as msal from "@azure/msal-node";

const msalConfig = {
  auth: {
    clientId: process.env.CLIENT_ID,
    authority: process.env.AAD_ENDPOINT + "/" + process.env.TENANT_ID,
    clientSecret: process.env.CLIENT_SECRET,
  },
};

const tokenRequest = {
  scopes: [process.env.GRAPH_ENDPOINT + "/.default"],
};

const apiConfig = {
  uri: process.env.GRAPH_ENDPOINT + "/v1.0/users",
};

const cca = new msal.ConfidentialClientApplication(msalConfig);

/**
 * Acquires token with client credentials.
 * @param {object} tokenRequest
 */
async function getToken(tokenRequest) {
  return await cca.acquireTokenByClientCredential(tokenRequest);
}

export default {
  apiConfig: apiConfig,
  tokenRequest: tokenRequest,
  getToken: getToken,
};

阅读电子邮件代码

export default router.get("/", async (req, res) => {
  try {
    const { email } = req.body;
    const token = await emailAuth.getToken(emailAuth.tokenRequest);
    // console.log(token);

    const url = `${emailAuth.apiConfig.uri}/${email}/messages`;
    const accessToken = token.accessToken;
    // console.log(url);
    // console.log(token.accessToken);

    let data = await fetch(url, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });

    data = await data.json();
    console.log(data);

    return send(res, RESPONSE.SUCCESS, data);
  } catch (err) {
    console.log(err);
    return send(res, RESPONSE.UNKNOWN_ERROR);
  }
});

已使用 Azure 完成

App registration

这是我的API权限 enter image description here

认证 enter image description here

需要读取给定电子邮件 ID 的用户的电子邮件,例如:

[email protected]

node.js azure microsoft-graph-api
1个回答
0
投票

注意:您需要利用委托流程或用户交互流程来获取个人 Outlook 帐户的邮件并生成访问令牌。还可以利用

/me/messages
端点。

通过选择“任何组织目录中的帐户(任何 Microsoft Entra ID 租户 - 多租户)和个人 Microsoft 帐户(例如 Skype、Xbox)”来注册 Microsoft Entra ID 应用程序

enter image description here

确保授予

Mail.Read
Mail.ReadWrite
委托类型的权限:

enter image description here

使用此 GitHub 示例 生成访问令牌。

http://localhost:3000/redirect
平台下添加重定向URL为
Mobile and desktop applications

enter image description here

此外,启用允许公共客户端流至“是”并保存:

enter image description here

生成访问令牌:

确保将范围传递为

Mail.read

app.get('/redirect', (req, res) => {
    // You can also build the tokenRequest object directly in the JavaScript file like this
    const tokenRequest = {
        // The URL from the redirect will contain the Auth Code in the query parameters
        code: req.query.code,
        scopes: ["Mail.read"],
        redirectUri: "http://localhost:3000/redirect",
    };

    // Pass the tokenRequest object with the Auth Code, scopes and redirectUri to acquireTokenByCode API
    clientApplication.acquireTokenByCode(tokenRequest).then((response) => {
        console.log("\nResponse: \n:", response);
        res.sendStatus(200);
    }).catch((error) => {
        console.log(error);
        res.status(500).send(error);
    });
});

现在使用上面的令牌并调用

me/messages
端点:

GET https://graph.microsoft.com/v1.0/me/messages

enter image description here

参考:

开发人员的 microsoft-authentication-library-for-js/lib/msal-node/docs/request.md · AzureAD/microsoft-authentication-library-for-js

© www.soinside.com 2019 - 2024. All rights reserved.