0
votes

I've looked at several similar issues with callbacks not working in passport, but I can't seem to get my specific case resolved.

   passport.use(new OAuth2Strategy({
    authorizationURL: 'http://localhost:3001/oauth2/authorize',
    tokenURL: 'http://localhost:3001/oauth2/token',
    clientID: 'ID',
    clientSecret: 'secret',
    passReqToCallback: true
},

    function (accessToken, refreshToken, profile, cb) {

        //This never happens

        User.findOrCreate({ exampleId: profile.id }, function (err, user) {
            return cb(err, user);
        });
    }
))

I've also tried doing it directly in the router

app.get('/test', passport.authenticate('oauth2', { failureRedirect: '/login' },
(err, user, info) => {
    console.log("Something work please");
}),
(req, res) => {
    res.send("OK");
}

None of that ever fires. What happens is the passport.authenticate just immediately returns the profile. Isn't it supposed to return that result to the callback (any of the ones I'm trying to utilize)?

Here's the profile object for reference

{
"_id": "<ID>",
"accessToken": "<AccessToken>",
"accessTokenExpiresAt": "2019-11-18T21:39:20.994Z",
"refreshToken": "<RefresToken>",
"refreshTokenExpiresAt": "2019-12-02T20:39:20.994Z",
"client": {
    "id": "ClientID"
},
"user": {
    "username": "<username>"
},
"__v": 0

Verified it's hitting this specific endpoint? Yes Provider server working? Yes Other endpoints working without passport? Yes

Edit: I was thinking it would make an API call, but it seems to be wanting to redirect the request so the response from the OAuth2 server is getting returned directly to the client instead of hitting the callback.

1

1 Answers

0
votes

Ensure you've told your app to use the passport strategy on your route.

app.use('/test', passport.authenticate('oauth2', {session: false}));

Edit: Also, check if it will return with the right cb function. This is an example of a find and update function of mine.

passport.use('oauth2', new OAuth2Strategy({
    authorizationURL: 'http://localhost:3001/oauth2/authorize',
    tokenURL: 'http://localhost:3001/oauth2/token',
    clientID: 'ID',
    clientSecret: 'secret',
    passReqToCallback: true
},
async (accessToken, refreshToken, profile, cb) => {
    try {
        var user = await User.findOne({
            where: {
                id: profile.id
            }
        })
        if (user) {
            console.log('user found');
            await user.update({
                // update user if needed
            })
        }
        return cb(null, user);
    }
    catch (error) {
        console.log(error)
        return cb(error, false, error.message);
    }
}));