Microsoft Graph API provides powerful capabilities to interact with Microsoft 365 services. In this guide, we’ll explore how to create calendar events using Microsoft Graph API with delegated permissions, leveraging the MSAL.js library for authentication and token acquisition.
Prerequisites
Azure App Registration:
Go to the Azure portal and register your app.
Note down the Application (Client) ID, Directory (Tenant) ID, and create a Client Secret.
Under "API permissions," add Calendar.ReadWrite delegated permission.
MSAL.js Library: Install MSAL.js in your project:
npm install @azure/msal-browser
Redirect URI: Configure the redirect URI in your Azure app registration and in your application.
Setting Up MSAL.js
First, initialize MSAL.js in your application:
import { PublicClientApplication } from "@azure/msal-browser";
const msalConfig = {
auth: {
clientId: "YOUR_CLIENT_ID", // Replace with your Application ID
authority: "https://login.microsoftonline.com/YOUR_TENANT_ID", // Replace with your Tenant ID
redirectUri: "http://localhost:3000", // Replace with your redirect URI
},
};
const msalInstance = new PublicClientApplication(msalConfig);
Logging In and Acquiring a Token
Use the MSAL.js library to log in and obtain an access token:
async function loginAndGetToken() {
try {
const loginResponse = await msalInstance.loginPopup({
scopes: ["Calendars.ReadWrite"] // Scope for creating calendar events
});
const account = loginResponse.account;
msalInstance.setActiveAccount(account);
const tokenResponse = await msalInstance.acquireTokenSilent({
account: account,
scopes: ["Calendars.ReadWrite"]
});
return tokenResponse.accessToken;
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
// Fallback to interactive login
const tokenResponse = await msalInstance.acquireTokenPopup({
scopes: ["Calendars.ReadWrite"]
});
return tokenResponse.accessToken;
} else {
console.error("Error acquiring token", error);
throw error;
}
}
}
Creating a Calendar Event
Once you have the access token, use it to call the Microsoft Graph API and create an event:
async function createEvent(accessToken) {
const endpoint = "https://graph.microsoft.com/v1.0/me/events";
const event = {
subject: "Team Meeting",
body: {
contentType: "HTML",
content: "Let's discuss the project updates."
},
start: {
dateTime: "2025-01-20T09:00:00",
timeZone: "Pacific Standard Time"
},
end: {
dateTime: "2025-01-20T10:00:00",
timeZone: "Pacific Standard Time"
},
attendees: [
{
emailAddress: {
address: "attendee@example.com",
name: "John Doe"
},
type: "required"
}
]
};
const options = {
method: "POST",
headers: {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify(event)
};
try {
const response = await fetch(endpoint, options);
if (response.ok) {
const eventData = await response.json();
console.log("Event created successfully:", eventData);
} else {
console.error("Failed to create event:", response.status, await response.text());
}
} catch (error) {
console.error("Error creating event:", error);
}
}
Bringing It All Together
Combine the functions to authenticate the user, acquire a token, and create an event:
(async function main() {
try {
const token = await loginAndGetToken();
await createEvent(token);
} catch (error) {
console.error("An error occurred:", error);
}
})();
Testing
Start your application and ensure the redirect URI matches the one configured in Azure.
Click the login button to authenticate the user.
Call the
createEvent
function and verify the event appears in the user's calendar.
Conclusion
Using Microsoft Graph API with MSAL.js simplifies integrating calendar functionalities into your application. With delegated permissions, you can access user-specific data securely. Follow this guide to enhance your applications with event creation capabilities!
If you need any assistance integrating Microsoft Graph API with an ASP.NET web application, feel free to reach out to me at lasantha26@gmail.com
No comments:
Post a Comment