0

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 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?

Alok
  • 7,734
  • 8
  • 55
  • 100
  • Could you decode the access token by pasting it in [jwt.ms](https://jwt.ms/) and check `scp` and `tid` claims? – Sridevi May 22 '23 at 11:56
  • Also check whether `d19680c7-8d06-4906-92bd-0e4c1b318f03` from error is your **tenant ID** or not where your application is registered? – Sridevi May 22 '23 at 11:59
  • Are you using personal Microsoft account or local Azure AD account(ends with .onmicrosoft.com) to sign-in? – Sridevi May 22 '23 at 12:18
  • @Sridevi: I am ussing personal microsoft account whose user name is my email address e.g. `something@gmail.com` – Alok May 22 '23 at 12:21
  • Did you assign Office 365 license to that user? – Sridevi May 23 '23 at 07:11
  • @Sridevi: I am able to use https://www.office.com/ using same account. I am able to create calendar evets using same `something@gmail.com`. – Alok May 23 '23 at 07:20
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/253779/discussion-between-sridevi-and-alok). – Sridevi May 23 '23 at 07:20
  • I have shared link with code in chat. – Alok May 23 '23 at 09:37
  • Could you try changing the **authority URL** to `https://login.microsoftonline.com/common/` as you are using personal Microsoft account? – Sridevi May 23 '23 at 11:45
  • yes with ending slash its same error. – Alok May 23 '23 at 12:21
  • Could you include [Overview](https://i.imgur.com/BLKVOrb.png) snapshot to know how you registered your application? – Sridevi May 25 '23 at 08:46
  • Have you created app registration in Azure AD **B2C** tenant by selecting **Accounts in any identity provider or organizational directory** (user flows) as account type? – Sridevi May 25 '23 at 13:08
  • 1
    @Sridevi: my problem is solved by answer given in this question. Thanks a lot for your efforts. – Alok Jun 09 '23 at 13:42

1 Answers1

1

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

enter image description here

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 enter image description here 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.

ShwetaM
  • 546
  • 2
  • 6