node.jsmicrosoft-graph-apiauth0adalmicrosoft-graph-calendar

CompactToken parsing failed with error code: 80049217 when using passport library to access Microsoft Graph API


I am using 'passport-azure-ad-oauth2' npm module, to get an access token, which I could then pass to the MS Graph API.

passport.use(new AzureAdOAuth2Strategy({
    clientID: process.env.OUTLOOK_CLIENT_ID,
    clientSecret: process.env.OUTLOOK_SECRET,
    callbackURL: '/auth/outlook/callback',
},
    function (accesstoken: any, refresh_token: any, params: any, profile, done) {
        logger.info('Completed azure sign in for : ' + JSON.stringify(profile));
        logger.info('Parameters returned: ' + JSON.stringify(params));
        const decodedIdToken: any = jwt.decode(params.id_token);
        logger.info('Outlook Access Token:' + accesstoken);
        logger.info('Decoded Token: ' + JSON.stringify(decodedIdToken, null, 2));

        process.env['OUTLOOK_ACCESS_TOKEN'] = accesstoken;
        // add new user with token or update user's token here, in the database

    }));

And then, using '@microsoft/microsoft-graph-client' npm module, to fetch Calendar events from the Graph API as follows:

try {
    const client = this.getAuthenticatedClient(process.env['OUTLOOK_ACCESS_TOKEN']);
    const resultSet = await client
                .api('users/' + userId + '/calendar/events')
                .select('subject,organizer,start,end')
                .get();
    logger.info(JSON.stringify(resultSet, null, 2));
} catch (err) {
    logger.error(err);
}

getAuthenticatedClient(accessToken) {
    logger.info('Using accestoken for initialising Graph Client: ' + accessToken);
    const client = Client.init({
        // Use the provided access token to authenticate requests
        authProvider: (done) => {
            done(null, accessToken);
        }
    });

    return client;
}

However, however, using the accessToken provided on Successful Login, I get the following error : CompactToken parsing failed with error code: 80049217

Any suggestions what am I doing incorrectly ???

UPDATE : These are the scope I am using : 'openid,profile,offline_access,calendars.read'

UPDATE : After editing the scopes a bit, now I am getting the following error : Invalid Audience.

On decoding the token received at jwt.ms, this is the value for 'aud': "00000002-0000-0000-c000-000000000000"

Is it the case that passport-azure-ad-oauth2 is the wrong library for retrieving tokens for MS Graph API ?


Solution

  • Turns out there is a passport library for microsoft-graph api : passport-microsoft

    I used MicrosoftStrategy from that package and everything seems to be working fine.

    passport-azure-ad-oauth2 is for the old Azure AD Graph API, while passport-microsoft is for the new Microsoft Graph API