none
Office365 API using JavaScript to create calendar events RRS feed

  • Question

  • I am trying to create a Single Page Application using JavaScript (jQuery) and adal.js to acces Office365 API.

    I have it working getting access to email (read) and calendar (read), but I cannot get writing an event to the calendar to work.

    I am using the REST endpoint specified here:

    https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations#Createevents

    The query I am sending is this:

                var event = {
                    "Subject": "Discuss the Calendar REST API",
                    "Body": {
                        "ContentType": "HTML",
                        "Content": "I think it will meet our requirements!"
                    },
                    "Start": {
                        "DateTime": "2016-01-21T18:00:00",
                        "TimeZone": "Pacific Standard Time"
                    },
                    "End": {
                        "DateTime": "2016-01-21T19:00:00",
                        "TimeZone": "Pacific Standard Time"
                    },
                    "Attendees": [
                      {
                          "EmailAddress": {
                              "Address": "myemail@domain.dk",
                              "Name": "Jesper Stocholm"
                          },
                          "Type": "Required"
                      }
                    ]
                };
    
                // Create calendar events
                jQuery.ajax({
                    type: 'POST',
                    url: postCalenderEndpoint,
                    data: JSON.stringify(event),
                    contentType: "application/json",
                    headers: {
                        'Accept': 'application/json',
                        'Authorization': 'Bearer ' + token,
                    },
    
                }).done(function (data) {
                    
                    //alert(JSON.stringify(data));
    
                }).fail(function (err) {
                    jQuery("#loginMessage").text('Error calling REST endpoint: ' + err.statusText + '\n' + err.responseText);
                }).always(function () {
                })
                ;

    HHowever, I am consistantly getting a 403 in response (Forbidden). The app configured in our Azure Active Directory has granted both read access and "full access" to the user's calendar, and the JavaScript can read from the calendar just fine.

    What am I missing here?

    Thank,

    /Jesper


    /Jesper www.idippedut.dk


    Monday, January 18, 2016 2:31 PM

Answers

  • Hi Jesper,

    Don’t find the detail document/article about ADAL js library. I'm trying to involve some senior engineers into this issue and it will take some time. Your patience will be greatly appreciated.

    On the other hand, this article about scope and resource that may benefit you.

    Regards

    Starain


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, January 21, 2016 6:19 AM
    Moderator

All replies

  • Hi Jesper,

    How do you get the access token? Does it has the write permission?

    Regards

    Starain


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, January 19, 2016 9:02 AM
    Moderator
  • Hi Starain,

    The code is live at http://oauth.idippedut.dk/oauth.html .

    The complete JavaScript is here:

    //https://www.itunity.com/article/calling-office-365-apis-jquery-adaljs-2758
    
    jQuery(function () {
        //authorization context
        var resource = 'https://outlook.office.com';
        var endpoint = 'https://outlook.office.com/api/v2.0/me/mailfolders/inbox/messages?$top=10';
        var calenderEndpoint = 'https://outlook.office.com/api/v2.0/me/calendarview?startDateTime=2016-01-18&endDateTime=2016-01-19';
        var postCalenderEndpoint = 'https://outlook.office.com/api/v2.0/me/events';
        var clientID = '28a707a5-0f11-4d93-8b88-6a918544da14';
        var tenantName = '365projectum.onmicrosoft.com';
        var authContext = new AuthenticationContext({
            instance: 'https://login.microsoftonline.com/',
            tenant: tenantName,
            clientId: clientID,
            postLogoutRedirectUri: window.location.origin,
            cacheLocation: 'localStorage'
        });
    
        //sign in and out
        jQuery("#signInLink").click(function () {
            authContext.login();
        });
        jQuery("#signOutLink").click(function () {
            authContext.logOut();
        });
    
        //save tokens if this is a return from AAD
        authContext.handleWindowCallback();
        authContext.handleWindowCallback();
    
        var user = authContext.getCachedUser();
        if (user) {  //successfully logged in
            //welcome user
            jQuery("#loginMessage").text("Welcome, " + user.userName);
            jQuery("#signInLink").hide();
            jQuery("#signOutLink").show();
    
            //call rest endpoint
            authContext.acquireToken(resource, function (error, token) {
                if (error || !token) {
                    jQuery("#loginMessage").text('ADAL Error Occurred: ' + error);
                    return;
                }
    
                // Get calendar events
                jQuery.ajax({
                    type: 'GET',
                    url: calenderEndpoint,
                    headers: {
                        'Accept': 'application/json',
                        'Authorization': 'Bearer ' + token,
                    },
                }).done(function (data) {
                    jQuery("#restDataEventName").text(data.value[0].Subject);
                    jQuery("#restDataEventStart").text(data.value[0].Start.DateTime + ' ' + data.value[0].Start.TimeZone);
                    //alert(JSON.stringify(data));
                        
                    }).fail(function(err) {
                    jQuery("#loginMessage").text('Error calling REST endpoint: ' + err.statusText);
                }).always(function() {
                })
                ;
    
                var event = {
                    "Subject": "Discuss the Calendar REST API",
                    "Body": {
                        "ContentType": "HTML",
                        "Content": "I think it will meet our requirements!"
                    },
                    "Start": {
                        "DateTime": "2016-01-21T18:00:00",
                        "TimeZone": "Pacific Standard Time"
                    },
                    "End": {
                        "DateTime": "2016-01-21T19:00:00",
                        "TimeZone": "Pacific Standard Time"
                    },
                    "Attendees": [
                      {
                          "EmailAddress": {
                              "Address": "jesper@lundstocholm.dk",
                              "Name": "Janet Schorr"
                          },
                          "Type": "Required"
                      }
                    ]
                };
    
                // Create calendar events
                jQuery.ajax({
                    type: 'POST',
                    url: postCalenderEndpoint,
                    data: JSON.stringify(event),
                    contentType: "application/json",
                    headers: {
                        'Accept': 'application/json',
                        'Authorization': 'Bearer ' + token,
                    },
                }).done(function (data) {
                    //alert(JSON.stringify(data));
                }).fail(function (err) {
                    jQuery("#loginMessage").text('Error calling REST endpoint: ' + err.statusText + '\n' + err.responseText);
                }).always(function () {
                })
                ;
            });
        }
        else if (authContext.getLoginError()) { //error logging in
            jQuery("#signInLink").show();
            jQuery("#signOutLink").hide();
            jQuery("#loginMessage").text(authContext.getLoginError());
        }
        else { //not logged in
            jQuery("#signInLink").show();
            jQuery("#signOutLink").hide();
            jQuery("#loginMessage").text("You are not logged in.");
        }
    });

    So I am calling the adal.js code to aquire the token.

    If I take the token aquired through adal.js and decode it on www.jwt.io, I get this:

    {
      "aud": "https://outlook.office.com",
      "iss": "https://sts.windows.net/ee357b2a-1bf9-42a6-baab-9772d85b28c1/",
      "iat": 1453204444,
      "nbf": 1453204444,
      "exp": 1453208344,
      "acr": "1",
      "amr": [
        "wia"
      ],
      "appid": "28a707a5-0f11-4d93-8b88-6a918544da14",
      "appidacr": "0",
      "family_name": "Stocholm",
      "given_name": "Jesper Lund",
      "ipaddr": "87.54.52.210",
      "name": "Jesper Lund Stocholm",
      "oid": "",
      "onprem_sid": "",
      "puid": "1003BFFD8EB3510C",
      "scp": "Calendars.Read Mail.Read",
      "sub": "",
      "tid": "e",
      "unique_name": "",
      "upn": "",
      "ver": "1.0"
    }

    (the values with empty strings have been removed by me, since I do now know if they would create a replay-security issue)

    So I guess that since the "scp"-value is "Calendars.Read Mail.Read", I do not have write permissions. At least that would explain the error.

    Question is, though: what do I do to fix it? The configuration of permissions on the app in Azure Active Directory is this:

    dDoes this make sense?


    /Jesper www.idippedut.dk

    Tuesday, January 19, 2016 12:06 PM
  • Hi Jesper,

    Based on your code, you are using OAuth 2.0 API and there is a scope parameter that is required when logon.

    You are using ADAL library, which you download it? Is this one? I think you need to apply the write permission when logon.

    Regards

    Starain


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, January 20, 2016 6:03 AM
    Moderator
  • Hi Starain,

    I am using the version you point to - v1.0.7

    http://oauth.idippedut.dk/scripts/adal.js

    Original file is here:

    https://github.com/AzureAD/azure-activedirectory-library-for-js/blob/master/lib/adal.js

    I have tried to figure out how to apply the scope when logging in, but sadly in vain. Do you have any pointers to how to use it with ADAL?

    The only place I can see I could add the scope is the "resource" configuration, but if I add the Scope specification from https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations#Createevents such that the configuration is this:

    jQuery(function () {
    
        //authorization context
        //var resource = 'https://outlook.office.com';
        var resource = 'http://outlook.office.com/Calendars.ReadWrite';
        // ... other stuff not touched
    });

    Then I get this error:

    ADAL Error Occurred: AADSTS50001: The application named http://outlook.office.com/Calendars.ReadWrite was not found in the tenant named 365projectum.onmicrosoft.com. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant.

    Any ideas?

    Thank you so much :-)


    /Jesper www.idippedut.dk

    Wednesday, January 20, 2016 8:11 AM
  • Hi Jesper,

    Don’t find the detail document/article about ADAL js library. I'm trying to involve some senior engineers into this issue and it will take some time. Your patience will be greatly appreciated.

    On the other hand, this article about scope and resource that may benefit you.

    Regards

    Starain


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, January 21, 2016 6:19 AM
    Moderator