Outlook REST API 403 error while trying to fetch user emails

734 Views Asked by At

I am trying to fetch emails from user's outlook mail using Outlook REST API. I have been able to successfully authenticate user and get user access token, however, when I try to make an AJAX call to Outlook REST API, I get the following error:

GET https://outlook.office.com/api/v2.0/me/messages?callback=jQuery31008093694845457056_1490285639120 403 (Forbidden)

Also, I get following error from error function callback of AJAX:

Object {readyState: 4, status: 404, statusText: "error"}

Here is my code:

var ADAL = new AuthenticationContext({
    instance: 'https://login.microsoftonline.com/',
    tenant: 'common', 
    clientId: '',        //Intentionally left blank here

    redirectUri: 'http://localhost:8383/',     
    callback: userSignedIn,
    popUp: true
});

function signIn() {
    ADAL.login();
}

function userSignedIn(err, token) {
    console.log('userSignedIn called');
    if (!err) {
        console.log(token);            //This works!
        fetchUserSentMails(token);
    } else {
        console.error("error: " + err);
    }
}

function fetchUserSentMails(token) {
    var user = ADAL.getCachedUser();
    console.log(user.profile.name);        //This works!

    $.ajax({                  //This doesn't work
        type: 'GET',
        crossDomain: true,
        url: 'https://outlook.office.com/api/v2.0/me/messages',
        dataType: 'jsonp',
        headers: {'Authorization': 'Bearer ' + token},
        success: function (res) {
            console.log(res);
        },
        error: function (x, t, m) {
            console.log(x);
            console.log(t);
            console.log(m);
        }
    });
}

What am I doing wrong??

2

There are 2 best solutions below

4
Jason Johnston On

The most likely answer is your token doesn't have the proper scope. Parse your token at https://jwt.io and see what you have in the scp claim.

It looks like you're missing a call to AcquireToken. The login method just signs the user in and gets their identity, it doesn't provide an access token. You need something like this:

ADAL.acquireToken("https://outlook.office.com", function(error, accessToken){
  if (error) {
    console.log('ERROR: ' + JSON.stringify(error));
  } else {
    fetchUserSentMails(accessToken);
  }
}
0
AidaNow On

I see that you are getting timeout error. I had the exact same issue with timeout and I could only fix this by manipulating adal.js library. In this library there is a timeout of 6 seconds and it seems like it is very tight for some applications being loaded locally. To give it a quick test, you can find LOADFRAME_TIMEOUT: '6000' in adal.js and replace it with LOADFRAME_TIMEOUT: '30000', which will give you 30 seconds to load your application. I hope it works for you!