jaredhanson / passport-google-oauth2

Google authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-google-oauth20/?utm_source=github&utm_medium=referral&utm_campaign=passport-google-oauth20&utm_content=about
MIT License
820 stars 153 forks source link

How to create multiple instance of Strategy? #77

Open lamlejobchat opened 3 years ago

lamlejobchat commented 3 years ago

How to add multiple callback config with same cliendId?

I have some code:

I want to register two instance 'GoogleStrategy' with two 'callbackURL' use for web and desktop app:

passport.use(
    new GoogleStrategy( 'google-desktop',
      { clientID, clientSecret, callbackURL: 'localhost:6060/login/desktop/callback' },
      async (_, __, tokenData, profile, done) => {}
    ),
  );
passport.use(
    new GoogleStrategy( 'google-web',
      { clientID, clientSecret, callbackURL: 'localhost:6060/login/web/callback' },
      async (_, __, tokenData, profile, done) => {}
    ),
  );

With each platform will have difference url for request authenticate:

router.get('/login/web', passport.authenticate('google-web', { scope: ['profile', 'email'] }));
router.get('/login/desktop', passport.authenticate('google-desktop', { scope: ['profile', 'email'] }));

We register callback from Google with each type 'google-web' and 'google-desktop':

router.get('/login/web/callback', (req, res, next) => {
  passport.authenticate('google-web', (error, data) => {

  })(req, res, next);
});
router.get('/login/web/callback', (req, res, next) => {
  passport.authenticate('google-desktop', (error, data) => {

  })(req, res, next);
});

But this code really not working because inside Strategy constructor, 'name' alway equal 'google'. I think I will custom 'name' is a input in Strategy constructor. Does that will destabilize the passport and not working?

lfa9603 commented 2 years ago

This is the closest solution I found: https://github.com/jaredhanson/passport/issues/50 . Seems to be working for me.

You must make sure that wherever you call authenticate or use functions you reference your custom strategy name. I encapsulated my strategies in a class with a strategy property to be able to call passport.authenticate(this.strategy, ....) and keep this nice and consistent