使用本地和 twitter 策略的 Passportjs 身份验证

Passportjs authentication with local and twitter strategies

我正在尝试 link 使用现有的登录用户会话进行 Twitter 并且我已经配置了如下通行证以使用本地和 Twitter 策略进行身份验证

//Configure passport to use Twitter Authentication strategy
passport.use(new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
    callbackURL: "http://localhost:4000/auth/twitter/callback",
    passReqToCallback: true
  },
  function(req, token, tokenSecret, profile, done) {
    // Although the req is being passed pack to my callback, the below function is not being executed at all
    if (!req.user) {
      console.log("Not already authenticated using local strategy")
    } else {
      console.log("Already Authenticated using local strategy, link twitter")
    }
  }
));

// Configure passport for local auth
passport.use(new localStrategy({
  usernameField: 'email_addr',
}, User.authenticate()));


passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

/ Link Twitter
app.get('/auth/twitter',
  passport.authenticate('twitter'));


app.get('/auth/twitter/callback', function(req, res) {
  if (req.isAuthenticated) {
    res.redirect("/")
  } else {
    res.redirect("/login")
  }
})

问题 #1:一切正常。但是,即使 req 被传回回调

,下面的嵌入式函数也没有在回调之前为我执行link twitter acct

function(req, token, tokenSecret, profile, done) {
  // Although the req is being passed pack to my callback, the below function is not being executed at all, with no error message

  if (!req.user) {
    console.log("Not already authenticated using local strategy")
  } else {
    console.log("Already Authenticated using local strategy")
  }
}

问题 #2:除了 req 之外,是否有办法将返回的 Twitter 配置文件传回回调?以便能够在 /auth/twitter/callback 上将其登录到控制台,同时保留经过身份验证的用户的本地会话

我想通了这个问题。显然,为twitter策略配置passport时的嵌入函数只有在身份验证成功时才会执行,失败可以在回调中处理。

//Configure passport to use Twitter Authentication strategy
passport.use(new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
    callbackURL: "http://localhost:4000/auth/twitter/callback",
    passReqToCallback: true
  },
  function(req, token, tokenSecret, profile, done) {
    //can perform any function in here as it will only be executed on successful Auth
  }
));
// Configure passport for local auth
passport.use(new localStrategy({
  usernameField: 'email_addr',
}, User.authenticate()));


passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// Link Twitter
app.get('/auth/twitter',
  passport.authenticate('twitter'));

app.get('/auth/twitter/callback',
  passport.authenticate('twitter', {
    failureRedirect: '/login'
  }),
  function(req, res) {
    //on successful auth 
    res.redirect('/home');
  });