Fetch microsoft outlook calendar events using graph api in Node.js.

huangapple go评论78阅读模式
英文:

Fetch microsoft outlook calendar events using graph api in Node.js

问题

我正在尝试创建一个最简单的日历应用程序,可以显示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');

// 使用您的身份验证配置初始化MSAL客户端
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);

// 创建一个Express应用程序
const app = express();

// 定义用于启动登录过程的路由
app.get('/login', async (req, res) => {
  const authCodeUrlParameters = {
    scopes: ['openid', 'profile', 'offline_access', 'Calendars.Read'],
    redirectUri: 'http://localhost:3000/redirect'
  };

  // 生成授权URL
  const authUrl = await msalClient.getAuthCodeUrl(authCodeUrlParameters);
  console.log('alok', authUrl)

  // 将用户重定向到授权URL
  res.redirect(authUrl);
});

// 定义用于处理重定向回调的路由
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 {
    // 使用授权码获取访问令牌
    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) {
    // 处理令牌获取错误
    console.log(error);
    res.send('Authentication failed.');
  }
});

// 启动服务器
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"
    }
  }
}

我尝试从https://stackoverflow.com/questions/54347728/calendar-endpoint-returns-organizationfromtenantguidnotfound 获取帮助,但仍然收到相同的错误。

我的clientIdclientSecretauthority都是正确的,这就是我能够获取令牌的原因。我缺少什么导致图形API调用出错?

英文:

I am trying to create the simplest calendar application that can show users calendar events for microsoft outlook users.

I am using @azure/msal-node for authentication.
I am using GET https://graph.microsoft.com/v1.0/me/calendar/events to fetch events

I am able to authenticate and get a token but getting error in graph api request.

Here is my code:

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');
});

I am getting response on graph api call

{
  "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"
    }
  }
}

I tried to get help from https://stackoverflow.com/questions/54347728/calendar-endpoint-returns-organizationfromtenantguidnotfound but still getting same error.

My clientId, clientSecret and authority are correct thats why I am able to get token.
What I am missing so getting error in graph api call?

答案1

得分: 1

你已在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中注册应用程序,支持的帐户类型如下:

Fetch microsoft outlook calendar events using graph api in Node.js.

并在authority中设置https://login.microsoftonline.com/common/。

但是,如果您只有个人Microsoft帐户的用户,请在注册应用程序时选择最后一个选项:

Fetch microsoft outlook calendar events using graph api in Node.js.

并在authority URL中设置https://login.microsoftonline.com/consumers/以获取有效的访问令牌。

注意:出于安全原因,个人Microsoft帐户的访问令牌无法解码。您只能使用jwt.ms解码id_token以用于个人帐户。

英文:

Based on your conversation with @Sridevi, you have registered your application in Azure AD B2C tenant.
To begin, it's important to note that Azure AD B2C is distinct from Azure AD. Unlike Azure AD, which caters to organizational users, Azure AD B2C is specifically designed for consumer applications, targeting non-organizational users or consumers.

Based on the configuration details you provided, the endpoint you're attempting to use in your application corresponds to Azure AD rather than Azure AD B2C.

In your application, you are trying to retrieve a token using the Azure AD endpoint but encountering an error ("OrganizationFromTenantGuidNotFound") because of a mismatch between the tenants. The application is registered in the Azure AD B2C tenant, which might be causing the issue when interacting with the Azure AD endpoint.

To resolve your issue,
You need to register your application in Azure AD with supported account types

Fetch microsoft outlook calendar events using graph api in Node.js.

and set https://login.microsoftonline.com/common/ in authority

However, If you have only users with Personal Microsoft Accounts, then select last option while registering the application
Fetch microsoft outlook calendar events using graph api in Node.js.
and set https://login.microsoftonline.com/consumers/ in the authority URL to get valid access token.

Note: Access token for personal Microsoft accounts can't be decoded due to security reasons. You can only able to decode id_token using jwt.ms for personal accounts.

huangapple
  • 本文由 发表于 2023年5月22日 19:37:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定