如何动态配置 Passportjs 策略?

cia*_*ben 4 javascript node.js express passport.js

我正在玩通行证,并以这种方式配置我的 twitter 登录:

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

我希望能够在运行时根据登录的用户配置以下值:(consumerKey, consumerSecret, callbackURL)。也就是说,每个用户都将拥有他们需要在 Twitter 上注册的 Twitter 应用程序。

有什么建议吗?

Jar*_*son 8

无需使用 提前注册策略passport.use(),策略可以直接传递给authenticate()(而不是传递策略名称)。

例如:

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);
}
Run Code Online (Sandbox Code Playgroud)

可以在此处找到有关此技术的更多信息:https : //medium.com/passportjs/authenticate-using-strategy-instances-49e58d96ec8c


rsp*_*rsp -2

您需要使用您的消费者密钥和消费者秘密,而不是用户的消费者密钥和消费者秘密。然后您的应用程序将能够使用 Twitter 对您的用户进行身份验证。但这些密钥和秘密用于向 Twitter API 验证您的应用程序。

请参阅此示例项目: