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