Search code examples
node.jsoauthpassport.jskoa2

How to configure OAuth Server to send profile information?


I have custom OAuth provider (koa2-oauth-server) running on port 8080.

I have a client application which uses Passport to authenticate the request using OAuth2Strategy.

The following code configures the passport for OAuth

passport.use(
    new OAuth2Strategy({
        tokenURL: 'http://localhost:8080/oauth/token',
        authorizationURL: 'http://localhost:8080/oauth/authorize',
        clientID: 'xxx',
        clientSecret: 'xxx',
        callbackURL: 'http://localhost:3000/oauth/redirect'
    }, (accessToken, refreshToken, profile, done) => {
        console.log(profile); // This is always empty object
        done(null, profile);
    })
);

And the following code generates the Access Token

router.post('/oauth/token', oauth.token(),
    (ctx,next) => {
        // TODO: Profile information not being sent
        const userid = ctx.state.oauth.token.user.id;
        ctx.body = db.users.find(function(aUser){
            return aUser.id == userid;
        })
    }
);

I want to receive profile information in the passport callback function. I tried sending the user profile information as seen in the second block of code but it did not work.

I tried reading the code of koa2-oauth-server and node-oauth2-server to figure out how to send the profile information but with no luck.

How should I configure the OAuth provider to send the profile information back to client?


Solution

  • I checked the source of passport-oauth2 and turns out this function was the culprit

    /**
     * Retrieve user profile from service provider.
     *
     * OAuth 2.0-based authentication strategies can overrride this function in
     * order to load the user's profile from the service provider.  This assists
     * applications (and users of those applications) in the initial registration
     * process by automatically submitting required information.
     *
     * @param {String} accessToken
     * @param {Function} done
     * @api protected
     */
    OAuth2Strategy.prototype.userProfile = function(accessToken, done) {
      return done(null, {});
    };
    

    I overloaded the function in my js file to match my requirements.