通过本地策略和Twitter策略进行Passportjs身份验证

时间:2020-09-02 16:42:36

标签: javascript node.js passport.js

我正在尝试将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传递回回调,也无法在回调之前执行以下嵌入函数来链接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上的控制台上,同时保留经过身份验证的用户的本地会话

1 个答案:

答案 0 :(得分:0)

我发现了问题。显然,只有在身份验证成功并且可以在回调函数中处理失败的情况下,才可以在配置用于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) {
    //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');
  });