在Node.js中使用图形API获取Microsoft Outlook日历事件

wj8zmpe1  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(383)

我试图创建最简单的日历应用程序,可以显示用户的Microsoft Outlook用户的日历事件。
我正在使用@azure/msal-node进行身份验证。
我正在使用GET https://graph.microsoft.com/v1.0/me/calendar/events获取事件
我能够进行身份验证并获得令牌,但在图形API请求中出现错误。
下面是我的代码:

const express = require('express');
const { PublicClientApplication, LogLevel } = require('@azure/msal-node');

// Initialize the MSAL client with your authentication configuration
const msalConfig = {
  auth: {
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    authority: `https://login.microsoftonline.com/${process.env.TENANT_ID}`,
    redirectUri: 'http://localhost:3000/redirect'
  },
  system: {
    loggerOptions: {
      loggerCallback(loglevel, message, containsPii) {
        console.log(message);
      },
      piiLoggingEnabled: false,
      logLevel: LogLevel.Info
    }
  }
};

const msalClient = new PublicClientApplication(msalConfig);

// Create an Express app
const app = express();

// Define a route for initiating the login process
app.get('/login', async (req, res) => {
  const authCodeUrlParameters = {
    scopes: ['openid', 'profile', 'offline_access', 'Calendars.Read'],
    redirectUri: 'http://localhost:3000/redirect'
  };

  // Generate the authorization URL
  const authUrl = await msalClient.getAuthCodeUrl(authCodeUrlParameters);
  console.log('alok', authUrl)

  // Redirect the user to the authorization URL
  res.redirect(authUrl);
});

// Define a route for handling the redirect callback
app.get('/redirect', async (req, res) => {
  const tokenRequest = {
    code: req.query.code,
    scopes: ['openid', 'profile', 'offline_access', 'Calendars.Read'],
    redirectUri: 'http://localhost:3000/redirect'
  };

  try {
    // Acquire an access token using the authorization code
    const response = await msalClient.acquireTokenByCode(tokenRequest);

    const token = response.accessToken;
    const graphEndpoint = 'https://graph.microsoft.com/v1.0/me/calendar/events';
    const resp = await fetch(graphEndpoint, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    const data = await resp.json();
    console.log('Calendar events:', data);
    res.send('Calendar events' + JSON.stringify(data));
  } catch (error) {
    // Handle the token acquisition error
    console.log(error);
    res.send('Authentication failed.');
  }
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});

我在图形API调用上得到响应

{
  "error": {
    "code": "OrganizationFromTenantGuidNotFound",
    "message": "The tenant for tenant guid 'd19680c7-8d06-4906-92bd-0e4c1b318f03' does not exist.",
    "innerError": {
      "oAuthEventOperationId": "213fd067-58a7-420a-bd93-64b4f68e6cae",
      "oAuthEventcV": "M17KB0OaSeGkiZmrisUKhA.1.1.1",
      "errorUrl": "https://aka.ms/autherrors#error-InvalidTenant",
      "requestId": "aee1392f-5824-432c-82ef-9083be5001af",
      "date": "2023-05-22T11:07:23"
    }
  }
}

我试图从Calendar endpoint returns OrganizationFromTenantGuidNotFound获得帮助,但仍然得到相同的错误。
我的clientIdclientSecretauthority是正确的,这就是为什么我能够得到令牌。
我错过了什么,所以在图形API调用中出错?

6rvt4ljy

6rvt4ljy1#

根据您与@Sridevi的对话,您已在Azure AD B2C租户中注册了应用程序。开始,请注意Azure AD B2C与Azure AD不同。与面向组织用户的Azure AD不同,Azure AD B2C是专为消费者应用程序设计的,面向非组织用户或消费者。
根据您提供的配置详细信息,您尝试在应用程序中使用的端点对应于Azure AD而不是Azure AD B2C。
在您的应用程序中,您尝试使用Azure AD端点检索令牌,但由于租户之间不匹配而遇到错误(“OrganizationFromTenantGuidNotFound”)。该应用程序已在Azure AD B2C租户中注册,这可能导致与Azure AD端点交互时出现问题。
要解决问题,您需要在Azure AD中使用支持的帐户类型注册应用程序

并将https://login.microsoftonline.com/common/设置为权限
但是,如果您只有使用个人Microsoft帐户的用户,则在注册应用程序

时选择最后一个选项,并在权限URL中设置https://login.microsoftonline.com/consumers/以获取有效的访问令牌。
注意:由于安全原因,无法对个人Microsoft帐户的访问令牌进行解码。您只能使用www.example.com为个人帐户解码id_tokenjwt.ms。

相关问题