Access Outlook Calendar Events From A Personal Hotmail Account Using Microsoft Graph API

136 Views Asked by At

My goal is to create an AWS Lambda function that will be invoked whenever a user submits an inquiry form on my website.

The form includes a date I want to use to retrieve the events on my personal Outlook calendar for that day.

I found a query that works in the graph explorer, but every combination of permissions and flows I tried on the Lambda and my local machine results in authentication errors.

My most recent attempt:

import axios from 'axios';

export const handler = async (event) => {
    const clientId = process.env.CLIENT_ID;
    const clientSecret = process.env.CLIENT_SECRET;
    const tenantId = process.env.TENANT_ID;
    const tokenUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
    //const calendarUrl = 'https://graph.microsoft.com/v1.0/me/calendar/events';

    const authParams = new URLSearchParams({
        grant_type: 'client_credentials',
        client_id: clientId,
        client_secret: clientSecret,
        scope: 'https://graph.microsoft.com/.default'
    });

    try {
        const tokenResponse = await axios.post(tokenUrl, authParams);
        const accessToken = tokenResponse.data.access_token;

        //const calendarUrl = 'https://graph.microsoft.com/v1.0/me/calendarView';
        const calendarUrl = "https://graph.microsoft.com/v1.0/users('{my-user-princpial-name}')/calendarView";
        const date = event.date; // The date for which you want to retrieve events
        const calendarParams = {
            startDateTime: `${date}T00:00:00-08:00Z`,
            endDateTime: `${date}T23:59:59-08:00Z`
        };

        const config = {
            headers: {
                Authorization: `Bearer ${accessToken}`,
            },
            params: calendarParams
        };

        const calendarResponse = await axios.get(calendarUrl, config);
        const events = calendarResponse.data.value;

        return {
            statusCode: 200,
            body: JSON.stringify(events)
        };
    } catch (error) {
        console.error('Error:', error.response.data.error);
        return {
            statusCode: 500,
            body: JSON.stringify({ error: 'An error occurred' })
        };
    }
};

This produces the error message:

The tenant for tenant guid '{my-tenant-id}' does not exist.

The tenant does exist, and the user I am attempting to access is the only user assigned to it.

The overall function is valid because when I switch the calendarUrl to the "/me" query and copy the token from the graph explorer, it works as intended.

Is this because I'm using a personal account?
I've seen things online that suggest that the API only works with personal accounts when the user manually logs in every time a request is made.

Is there some way around this or some flow that would get me the token?
It doesn't have to be a fix for this particular code, any solution to get calendar events from my personal Outlook calendar.

I'm considering using a webdriver to scrape directly from the web app, or migrating my calendar to a different calendar service with a more user-friendly API.

0

There are 0 best solutions below