Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically configure Passportjs strategies?

I am playing around with passport, and configuring my twitter login this way:

passport.use(new TwitterStrategy({
    consumerKey: '*****',
    consumerSecret: '*****',
    callbackURL: "http://blabla/callback"
  },
  function(token, tokenSecret, profile, done) {
    done(null, profile)
  }
));

I want to be able to configure this values: (consumerKey, consumerSecret, callbackURL) on runtime, based on the logged user. That is, each user will have their on Twitter app that they need to register with Twitter.

Any advice?

like image 428
ciaoben Avatar asked Mar 28 '17 14:03

ciaoben


1 Answers

Instead of registering a strategy ahead-of-time with passport.use(), the strategy can be passed directly to authenticate() (as opposed to passing the strategy name).

For example:

function login(req, res, next) {
  var user = req.user;
  var consumerKey = getConsumerKeyForUser(user);
  // Create a strategy instance specifically for this user.
  var strategy = new TwitterStrategy({ consumerKey: consumerKey }, ...);
  // Authenticate using the user-specific strategy
  passport.authenticate(strategy)(req, res, next);
}

More information on this technique can be found here: https://medium.com/passportjs/authenticate-using-strategy-instances-49e58d96ec8c

like image 164
Jared Hanson Avatar answered Oct 17 '22 08:10

Jared Hanson