getting 401 with no message while creating teams meeting link using azure graph client in NodeJS,JS

50 views Asked by At

Below is my code. I am new to Azure.

permissions I set. permissions

const { startDateTimeAsync, endDateTimeAsync } = require('./dateTimeFormat');
const { ClientSecretCredential } = require('@azure/identity');
const { Client } = require('@microsoft/microsoft-graph-client');
const { TokenCredentialAuthenticationProvider } = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials');
require('isomorphic-fetch');
require('dotenv').config()

let clientSecretCredential;
let appGraphClient;

function ensureGraphForAppOnlyAuth() {
    if (!clientSecretCredential) {
        clientSecretCredential = new ClientSecretCredential(
            process.env.AZURE_TENANT_ID,
            process.env.AZURE_CLIENT_ID,
            process.env.AZURE_CLIENT_SECRET
        );
    }

    if (!appGraphClient) {
        const authProvider = new TokenCredentialAuthenticationProvider(
            clientSecretCredential, {
            scopes: ['https://graph.microsoft.com/.default']
        });

        appGraphClient = Client.initWithMiddleware({
            authProvider: authProvider
        });
    }
}

async function createNewMeetingAsync(userId) {
    ensureGraphForAppOnlyAuth();
    let startTime = await startDateTimeAsync();
    let endTime = await endDateTimeAsync();
    userId = `8:acs:77bac1c4-cf55-4b91-b60c-5a396df98b1c_0000001e-f63c-164b-9f3b-8e3a0d00568e`
    const newMeeting = `/users/${userId}/calendar/events`;

    const event = {
        subject: 'Customer Service Meeting',
        start: {
            dateTime: startTime,
            timeZone: 'UTC'
        },
        end: {
            dateTime: endTime,
            timeZone: 'UTC'
        },
        isOnlineMeeting: true,
        // isOrganizer: true
    };

    try {
        const newEvent = await appGraphClient.api(newMeeting).post(event);
        return newEvent;
    } catch (error) {
        console.error('Error creating new meeting:', error);
        throw error;
    }
}

module.exports = createNewMeetingAsync;

Here is error message I am receving

body:ReadableStream {Symbol(kType): 'ReadableStream', Symbol(kState): {…}, Symbol(nodejs.webstream.isClosedPromise): {…}, Symbol(nodejs.webstream.controllerErrorFunction): ƒ}

code:null

date:Tue Mar 19 2024 07:27:56 GMT-0400 (Eastern Daylight Time)

requestId:null

statusCode:401

stack:'Error\n at new GraphError (C:\Users\Michael's\projects\server\node_modules\@microsoft\microsoft-graph-client\lib\src\GraphError.js:34:28)\n at Function. (C:\Users\Michael's\projects\server\node_modules\@microsoft\microsoft-graph-client\lib\src\GraphErrorHandler.js:97:30)\n at step (C:\Users\Michael's\projects\server\node_modules\tslib\tslib.js:195:27)\n at Object.next (C:\Users\Michael's\projects\server\node_modules\tslib\tslib.js:176:57)\n at C:\Users\Michael's\projects\se…mise ()\n at Object.__awaiter (C:\Users\Michael's\projects\server\node_modules\tslib\tslib.js:165:16)\n at GraphErrorHandler.getError (C:\Users\Michael's\projects\server\node_modules\@microsoft\microsoft-graph-client\lib\src\GraphErrorHandler.js:87:24)\n at GraphRequest. (C:\Users\Michael's\projects\server\node_modules\@microsoft\microsoft-graph-client\lib\src\GraphRequest.js:315:84)\n at step (C:\Users\Michael's... [[Prototype]]: Error

I follow these articles https://medium.com/@rcpatil12c/create-a-teams-meeting-with-microsoft-graph-api-8b1cdefe825f https://devblogs.microsoft.com/microsoft365dev/from-zero-to-hero-build-a-meetings-app-with-azure-communication-services-and-microsoft-teams-part-2/

But on My sidde, its not working.

Any help is highly appriciable.

1

There are 1 answers

0
Pravallika KV On

Follow below steps to create OnlineMeeting Link using NodeJs code:

  • Grant API permissions- OnlineMeetings.ReadWrite:

enter image description here

Use below code to create OnlineMeeting Link:

Code Snippet:

const { Client } = require('@microsoft/microsoft-graph-client');
const { TokenCredentialAuthenticationProvider } = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials');

// Create an interactive auth provider
const { InteractiveBrowserCredential } = require('@azure/identity');
const credential = new InteractiveBrowserCredential({
    tenantId: '<your_tenant_id>',
    clientId: '<your_client_id>'
});
const authProvider = new TokenCredentialAuthenticationProvider(credential, {
    scopes: ['User.Read'],
  });
  
const graphClient = Client.initWithMiddleware({ authProvider: authProvider });

userId='<user_object_id>'
const newMeeting = `/users/${userId}/onlineMeetings`;

// Define the meeting parameters
const meetingDetails = {
        startDateTime:'2024-03-21T17:30:34.2444915-07:00',
        endDateTime:'2024-03-21T18:00:34.2464912-07:00',
        subject:'User Token Meeting'
};

// Create the Teams meeting link using the Graph client
graphClient.api(newMeeting).post(meetingDetails)
    .then((response) => {
        console.log(`Meeting link: ${response.joinWebUrl}`);
    })
    .catch((error) => {
        console.log(`Error creating meeting link: ${error}`);
    });

Add Redirect URI in the App registrations=><your_App>=>Authentication=>Add Platform=>Select Mobile and desktop applications

enter image description here

  • Also Enable Allow Public Client FLows in the Authentication, as we are acquiring tokens interactively:

enter image description here

Able to create the meeting link:

enter image description here

Console Response:

C:\Users\uname\teamsmeet>node meet.js

Meeting link: https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZTkzZTFmZGYtZGM2ZC00NjczLWE3NTYtNmFhYTc0ODBhMGZh%40thread.v2/0?context=%7b%22Tid%22%3a%222773f7fd-d343-4afe-8230-e735719f9b0b%22%2c%22Oid%22%3a%22a92f57da-145e-4064-aa7e-c7f33e28fe01%22%7d

enter image description here