Search code examples
node.jspassport.jsaccess-tokenpassport-azure-ad

Need help in getting an access-token using Passport-azure-ad npm module and OIDCStrategy


I am trying to call Microsoft Graph API from my NodeJS express webapp and I am not able to fetch an access token from AAD.

I am able to successfully login as well as able to get the user's profile,(able to get the code and id_token) and next I want to fetch the access token so that I call make the Graph Api call.

Can someone please help understand how can I fetch the access token from the OIDCStrategy?


Solution

  • I found the fix for the same.

    passport.use(new OIDCStrategy({
            identityMetadata: configAuth.creds.identityMetadata,
            clientID: configAuth.creds.clientID, 
            responseType: configAuth.creds.responseType,
            responseMode: configAuth.creds.responseMode,
            redirectUrl: configAuth.creds.redirectUrl, 
            allowHttpForRedirectUrl: configAuth.creds.allowHttpForRedirectUrl,
            clientSecret: configAuth.creds.clientSecret,
            validateIssuer: configAuth.creds.validateIssuer,
            isB2C: configAuth.creds.isB2C,
            issuer: configAuth.creds.issuer,
            passReqToCallback: configAuth.creds.passReqToCallback, 
            scope: configAuth.creds.scope,
            loggingLevel: configAuth.creds.loggingLevel, 
            nonceLifetime: configAuth.creds.nonceLifetime,
            nonceMaxAmount: configAuth.creds.nonceMaxAmount,
            useCookieInsteadOfSession: configAuth.creds.useCookieInsteadOfSession,
            cookieEncryptionKeys: configAuth.creds.cookieEncryptionKeys,
            clockSkew: configAuth.creds.clockSkew,
        }, (req, iss, sub, profile, access_token, refresh_token, params, done) => {
            console.log(`Profile >>>> ${JSON.stringify(profile)}`);
            if(!profile.oid) {
                return done(new Error("No oid found"), null);
            }
            profile.tokens = params;
            // console.log(`Access-Token >>>> ${access_token}`);
            // console.log(`Refresh-Token >>>> ${refresh_token}`);       
            // console.log(`Profile >>>>>>>>>>>>>> ${JSON.stringify(profile)}`);
            process.nextTick(() => {
                findByOid(profile.oid, (err, user) => {
                    if(err) {
                        return done(err);
                    }
                    if(!user) {
                        users.push(profile);
                        return done(null, profile);
                    }
                    return done(null, user);      
                });
            });
        }));